无法使用Rails URL参数

时间:2012-10-16 13:23:46

标签: ruby-on-rails ruby-on-rails-3 link-to actioncontroller

我通过suggestion_id传递link_to参数,以便将其保存为其他控制器中create操作的一部分。

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

以下是结果网址:

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

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

@interested.suggestion_id = params[:suggestion_id]
但是,事实并非如此。每当创建“感兴趣”对象时,suggestion_id为零。给出了什么以及为什么我找不到文档来帮助我解决这个问题?不要告诉我看here,因为我已经做过了。这不是很有帮助。

1 个答案:

答案 0 :(得分:1)

也许这样试试:

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

new_interested_path方法已经表明它正在使用'interest'资源,因此控制器名称不需要(也不应该)传入。并且该方法不应该是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