Ruby-on-rails rails - 在 link_to 上传递 id 参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5268254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:39:08  来源:igfitidea点击:

rails - Pass id parameter on a link_to

ruby-on-railsruby

提问by ChrisWesAllen

I'm trying to pass the parameter of the current page(id) to the next page so I can create a dependent model entry.

我正在尝试将当前页面(id)的参数传递到下一页,以便我可以创建一个依赖模型条目。

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) %>

Which creates and performs the url.... "http://localhost:3000/bids/new.2"

它创建并执行 url .... "http://localhost:3000/bids/new.2"

I have

我有

def new
    @bid = Bid.new
    @project =  Project.find(params[:id])
end

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?

怎么回事,我怎么传不了id?

回答by BitOfUniverse

If your bids are not nested resource of the project, then you can add project_id as parameter to the path:

如果您的投标不是项目的嵌套资源,那么您可以将 project_id 作为参数添加到路径中:

<%= link_to "New Bid", new_bid_path(:project => @project.id) %>

<%= link_to "New Bid", new_bid_path(:project => @project.id) %>

def new  
  @bid = Bid.new  
  @project =  Project.find(params[:project])  
end

otherwise:

除此以外:

#routes.rb

map.resources :projects do |project|  
  project.resources :bids
end

<%= link_to "New Bid", new_project_bid_path(@project) %>

<%= link_to "New Bid", new_project_bid_path(@project) %>

def new  
  @project =  Project.find(params[:project_id])    
  @bid = @project.bids.build  
end  

回答by Gareve

A good approach to this kind of problems, its to see what are you sending with the params. This can be done with debug.

解决这类问题的一个好方法,就是看看你用参数发送了什么。这可以通过调试来完成。

<%= debug params # or any variable%>

With that information you will see (and learn) what kind of params are you sending to a controller.

有了这些信息,您将看到(并了解)您发送给控制器的参数类型。