1

Say I've got a standard new method in a controller:

def new
  @doc = Doc.new
  respond_to do |format|
    format.html
    format.json { render json: @doc }
  end
end

How would I facilitate passing an argument through it, i.e.:

def new(i)
  ...
end

To permit me to write something like this in the view:

<%= link_to(e.name, new_doc_path(e.id)) %>

Cheers!

1 Answer 1

7

Rails doesn't work like that. If you want to pass anything to the controller you have to use the params hash. In your example:

View:

<%= link_to(e.name, new_doc_with_parameter_path(e.id)) %>

Controller:

def new
  id = params[:id]
  # do something with `id`
end

For this to work you have to change your routes so that you can pass an id via the URL to your new action:

get "/docs/new/:id" => "docs#new", :as => :new_doc_with_parameter

Although the above should work, in your case it may be better to have a look at Nested Resources.

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

6 Comments

That seems like it'll work, but new_doc_path(e.id) gives me a URL that looks like .../doc/new.3. Any thoughts?
What are you trying to do exactly? What kind of object is e? You may want to have a look at Nested Resources.
@mileorsohigh, I updated my answer, but it may be better to use Nested Resources. Not sure if that's appropriate in your situation though.
e loops through records from a different model and each doc record has to record which e was selected. Does that makes sense?
So Doc belongs_to :e in your model? If so, you can use nested resources. See my link above. If not, try my updated answer.
|

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.