我想知道如何操作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
发布于 2013-01-22 00:56:12
Chagne the if params[:occurrence_id] to if params[:registration][:occurrence_id]
这就是Rails如何处理属于html文档中特定对象的属性。
表单中可能有其他输入,或者文档中有多个对象,这就是它们的组织方式。
如果你有意想要提到的行为,那么你必须使用form_tag而不是form_for。
https://stackoverflow.com/questions/14443453
复制相似问题