1

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Awesome! although now I'm getting "ActiveModel::ForbiddenAttributesError"
You're now running into Rails' strong parameters. You should be able to find some explanations googling for that.
1
@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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.