rails - 在 link_to 上传递 id 参数 [英] rails - Pass id parameter on a link_to
问题描述
我正在尝试将当前页面 (id) 的参数传递到下一页,以便我可以创建依赖模型条目.
I'm trying to pass the parameter of the current page(id) to the next page so I can create a dependent model entry.
即项目有标,标属于项目.
i.e. Projects have bids, bids belong to projects.
所以在项目的展示页面上,我添加了链接
So on the show page for a project I added the link
<%= link_to "New Bid", new_bid_path(@project) %>
创建并执行 url.... "http://localhost:3000/bids/new.2"
Which creates and performs the url.... "http://localhost:3000/bids/new.2"
我有
def new
@bid = Bid.new
@project = Project.find(params[:id])
end
在出价控制器中,但我不断收到错误无法找到没有 ID 的项目"
in the bids controller but I keep getting the error "Couldn't find Project without an ID"
???
怎么回事,我怎么传不了id?
Whats going on, how come I can't pass the id?
推荐答案
如果你的bids不是项目的嵌套资源,那么你可以在路径中添加project_id作为参数:
If your bids are not nested resource of the project, then you can add project_id as parameter to the path:
<%= link_to "New Bid", new_bid_path(:project => @project.id) %>
def new
@bid = Bid.new
@project = Project.find(params[:project])
end
否则:
#routes.rb
map.resources :projects do |project|
project.resources :bids
end
<%= link_to "New Bid", new_project_bid_path(@project) %>
def new
@project = Project.find(params[:project_id])
@bid = @project.bids.build
end
这篇关于rails - 在 link_to 上传递 id 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!