Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an Angular application that sends http requests to a rails server. I'd like to make a request to create a record (in the table SavedQueries).

The Angular app is actually making a very simple http request right now, like

$.post('http://10.241.16.159:3000/api/save_query', {'saved_query':1}); 

That javascript request gets routed to this Rails action:

def create
  @saved_query = SavedQuery.new(params[:saved_query])

  if @saved_query.save
    render json: @saved_query, status: :created, location: @saved_query
  else
    render json: @saved_query.errors, status: :unprocessable_entity
  end
end

However, instead of returning the appropriate json, the rails server logs a 500 error:

Started POST "/api/save_query" for 172.25.82.146 at 2014-07-31 19:14:06 +0000
Processing by SavedQueriesController#create as */*
  Parameters: {"saved_query"=>"1"}
Completed 500 Internal Server Error in 0ms

ArgumentError (When assigning attributes, you must pass a hash as an argument.):
  app/controllers/saved_queries_controller.rb:21:in `create'

So my question is, clearly by looking at the logs from the Rails server, we can see that the params passed was a hash, but the ArgumentError thrown says that the problem was that a hash must be passed as an argument.

What am I missing here?

share|improve this question

2 Answers 2

up vote 3 down vote accepted

You are receiving these parameters:

Parameters: {"saved_query"=>"1"}

ie, params[:saved_query] returns "1". Thus, when you do

@saved_query = SavedQuery.new(params[:saved_query])

you are really doing

@saved_query = SavedQuery.new("1")

and that's not going to work, as SavedQuery.new expects a Hash, not a String.

If instead you do

@saved_query = SavedQuery.new(params)

it should work.

share|improve this answer
    
Awesome! although now I'm getting "ActiveModel::ForbiddenAttributesError" –  johncorser 23 mins ago
1  
You're now running into Rails' strong parameters. You should be able to find some explanations googling for that. –  Jakob S 18 mins ago
@saved_query = SavedQuery.new(params[:saved_query])

Your .new on SavedQuery is essentially calling SavedQuery.new("1"), and Rails is having a problem with the value not having a key.

SavedQuery.new() #=> if no values are required

SavedQuery.new(age:1) #=> if there is an int column within the SavedQuery model, for example

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.