6

This is probably a very simple fix but I've been unable to find an answer just yet.

My application has orders and tasks. Orders have many tasks. When a user clicks new task in the show order view, it passes the order.id:

<%= link_to "New Task", new_task_path(:order_id=> @order.id) %>

The url shows:

/tasks/new?order_id=1

I just don't know how to extract this and use it in my form? I have tried:

<%= f.text_field :order_id, :value => @order_id %>

But it's not working.

1
  • Typo in :value => @order_id. Shouldn't it be :value => @order.id ? Commented Jun 10, 2011 at 13:07

2 Answers 2

2

You can do:

<%= f.text_field :order_id, :value => params[:order_id] %>

Alternately, capture the value (with params) in the controller and assign it to @order_id there.

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

2 Comments

@Jenny Please see my answer. This is absolutely the wrong way to do this in Rails.
-1

You are doing this wrong, which is a big deal in Rails where convention-over-configuration is such an important ideal.

If an order has many tasks, your route should look like this:

/orders/:order_id/tasks/new

And your routes should be configured thusly:

resources :orders do
  resources :tasks
end

You should [almost] never find yourself passing around record ids in the query string. In fact, you should almost never find yourself using query strings at all in Rails.

1 Comment

Nested resources aren't always appropriate. Some people think they're never appropriate, but I won't start that argument here. Even if you think they're sometimes appropriate, it's not 100% clear from the question that orders to tasks is an ownership rather than association relationship. I agree that this is a good option, but I object to calling other options "absolutely the wrong way to do this in Rails," to quote your other comment. Consider, e.g., if an "order" is an optional field on a task.

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.