Question

I'm passing a suggestion_id parameter via link_to so that it can be saved as part of a create action in a different controller.

<%= link_to "I'm interested", new_interested_path(:controller => :interested, 
    :suggestion_id => suggestion.id, :method => :get), :class => 'btn btn-mini' %>

Here is the resultant URL:

http://localhost:3000/interesteds/new?controller=interested&method=get&suggestion_id=1

According to this, I should be able to use the following code to access the suggestion_id parameter in my create action in this other controller:

@interested.suggestion_id = params[:suggestion_id]

This is not true, however. Whenever an "interested" object is created the suggestion_id is nil. What gives and why can't I find documentation to help me with this? And don't tell me to look here because I've already done that as well. It was not super helpful.

Was it helpful?

Solution

Perhaps try it like this:

<%= link_to "I'm interested", new_interested_path(:suggestion_id => suggestion.id), :method => :get, :class => 'btn btn-mini' %>

The new_interested_path method already indicates it is using the 'interested' resource and thus the controller name doesn't need to (and shouldn't) be passed in. And the method shouldn't be part of the URL, it's the http method that rails will use when sending the request to the URL.

Your point regarding suggestion_id being nil would depend on what you are trying to do. In your case you are not accessing the create action, but rather the new action which you may use to initialize an object for form rendering. In order to get the suggestion_id passed to the create action on submit, your new.html.erb view template would need to have a field (possibly a hidden field) that assigns that attribute - something like this:

form_for @interested, interesteds_path do |f|
  ... # other fields
  f.hidden_field :suggestion_id
  f.submit
end

When this form is submitted, params[:interested] would contain values for all the fields that were populated (including suggestion_id) and can be used to build and create a new ActiveRecord object.

Your controller actions should look something like this:

def new
  @interested = Interested.new(:suggestion_id => params[:suggestion_id])
end

def create
  @interested = Interested.new(params[:interested])
  if @interested.save
    # do something
  else
    # alert user
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top