无法使用Rails URL参数



我通过link_to传递一个suggestion_id参数,这样它就可以作为create操作的一部分保存在另一个控制器中。

<%= link_to "I'm interested", new_interested_path(:controller => :interested, 
:suggestion_id => suggestion.id, :method => :get), :class => 'btn btn-mini' %>

以下是结果URL:

http://localhost:3000/interesteds/new?controller=interested&method=get&suggestion_id=1

根据这一点,我应该能够使用以下代码来访问我在另一个控制器中的创建操作中的suggestion_id参数:

@interested.suggestion_id = params[:suggestion_id]

然而,事实并非如此。每当创建一个"感兴趣"的对象时,suggestion_id都是nil。什么给了我,为什么我找不到文档来帮助我?不要让我看这里,因为我也已经看过了。这并没有太大的帮助。

也许可以这样尝试:

<%= link_to "I'm interested", new_interested_path(:suggestion_id => suggestion.id), :method => :get, :class => 'btn btn-mini' %>

new_interested_path方法已经表明它正在使用"感兴趣的"资源,因此控制器名称不需要(也不应该)传入。该方法不应该是URL的一部分,它是rails在向URL发送请求时使用的http方法。

关于suggestion_id为零的观点将取决于您尝试做什么。在您的情况下,您不是在访问create操作,而是可以用于初始化对象以进行表单呈现的new操作。为了在提交时将suggestion_id传递给create操作,您的new.html.erb视图模板需要有一个分配该属性的字段(可能是隐藏字段),类似于以下内容:

form_for @interested, interesteds_path do |f|
... # other fields
f.hidden_field :suggestion_id
f.submit
end

提交此表单时,params[:interested]将包含已填充的所有字段(包括suggestion_id)的值,并可用于构建和创建新的ActiveRecord对象。

你的控制器动作应该是这样的:

def new
@interested = Interested.new(:suggestion_id => params[:suggestion_id])
end
def create
@interested = Interested.new(params[:interested])
if @interested.save
# do something
else
# alert user
end
end

最新更新