如何操作form_for以更改params []被发送到控制器的方式?

时间:2013-01-21 16:52:46

标签: ruby-on-rails

我想知道如何操作form_for以更改params []被发送到Controller的方式。

我使用以下表单发布到Registration#create controller:

<%= form_for @registration, method: :post do |form| %>
    <div class="form form-actions">
      <%= form.hidden_field :occurrence_id, :value => @occurrence.id %>
      <%= submit_tag "Yes, register", class: 'btn btn-primary' %>
      <%=  link_to "Cancel", root_path, class: 'btn' %>
    </div>
<% end %>

这是注册#创建控制器:

def create
  if params[:occurrence_id]
    @occurrence = Occurrence.find(params[:occurrence_id])
    @registration = Registration.new(registration_date: Date.today, user: current_user, occurrence: @occurrence)
    if @registration.save
      flash[:success] = "Course registration saved with success."
    else
      flash[:error] = "There was a problem saving the registration."
    end
    redirect_to occurrence_path(@occurrence)
  else
    flash[:error] = "Occurrence missing"
    redirect_to root_path
  end
end

现在我的params [:occurrence_id]没有被评估,因为表单正在发送隐藏字段,如下所示:

{"utf8"=>"✓",
 "authenticity_token"=>"5RFiAq3DiqauNzSpnXIcPzWEl9UuGqoXfYAvRiB6GKk=",
 "registration"=>{"occurrence_id"=>"2"},
 "commit"=>"Yes,
 register"}

我“期待”这个(我对RoR知之甚少)

{"utf8"=>"✓",
 "authenticity_token"=>"5RFiAq3DiqauNzSpnXIcPzWEl9UuGqoXfYAvRiB6GKk=",
 "occurrence_id"=> "2",
 "commit"=>"Yes,
 register"}

那么如何更改我的表单以便发送params [:occurrence_id]而不是params [:registration] [:occurrence_id]?

1 个答案:

答案 0 :(得分:2)

查看if params[:occurrence_id]if params[:registration][:occurrence_id]

这就是Rails如何设法处理属于html文档中特定对象的属性。

表单中可能还有其他输入或文档上有多个对象,这将是如何组织的。

如果您有理由想要提及的行为,那么您必须使用form_tag而不是form_for。