1

我想知道如何操作 form_for 以更改将 params[] 发送到我的控制器的方式。

我正在使用此表单向 Registration#create 控制器发布:

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

这是 Registration#create 控制器:

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]?

4

1 回答 1

2

更改if params[:occurrence_id]if params[:registration][:occurrence_id]

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

There might be other inputs in the form or multiple objects on a document, this how they will get organized.

If you intentioally want mentioned behaviour then you must use the form_tag instead of form_for.

于 2013-01-21T16:56:11.777 回答