Ruby on Rails Passing Parameter In URL

百般思念 提交于 2019-12-21 13:05:20

问题


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:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/6306690/ruby-on-rails-passing-parameter-in-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!