我有一个索引视图,显示所有可用的类,我想要一个“注册为类”的链接,将我重定向到“注册”表单并填写其他一些值,并在创建注册时保存我填写的值加上刚刚通过方法
的链接传递的类的外键类索引:
<h1>Listof classes</h1>
<table>
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>Description</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<% @classes.each do |class| %>
<tr>
<td><%= class.id %></td>
<td><%= class.name %></td>
<td><%= class.description %></td>
<td><%= link_to 'sign up!', new_sign_up_path(:class_id => class.id), method: :post %></td>
</tr>
<% end %>
</tbody>
</table>
sign_up控制器:
class SignUpsCOntroller < ApplicationController
before_action :set_sign_ups, only: [:show, :edit, :update, :destroy]
# GET /sign_ups/new
def new
@sign_up = SignUp.new
end
def set_sign_ups
@sign_up = SignUp.find(params[:id])
end
def sign_up_params
params.require(:sign_up).permit(:date, :status, :type, :class_id)
end
end
我的注册形式:
<%= form_for(@sign_up) do |f| %>
<div class="field">
<%= f.label :date %><br>
<%= f.date_select :date %>
</div>
<div class="field">
<%= f.label :status %><br>
<%= f.check_box :status %>
</div>
<div class="field">
<%= f.label :type %><br>
<%= f.number_field :type %>
</div>
<div class="field">
<%= f.hidden_field :class_id %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
当我保存它时它没有保存class_id ...我已经尝试将其解析为整数我已经尝试过没有隐藏的字段但是它总是把它作为空白传递给它保存...任何想法?
答案 0 :(得分:2)
您只是在params[:class_id]
上使用额外参数传递link_to
。但是,您的表单适用于具有class_id
属性的对象,因此期望您的@sign_up
对象具有class_id
属性。
基本上,对于您的new
操作,您需要使用@sign_up
为参数设置class_id
:
def new
@sign_up = SignUp.new
@sign_up.class_id = params[:class_id] if params.has_key?(:class_id)
end
这会将class_id
设置为从link_to
网址传入的参数。
然后您的表单应该可以正常工作,因为f.hidden_field
会查看class_id
上@sign_up
的当前值,并将其设置为输入值。此时您尚未保存它并不重要 - form_for
将使用未保存的状态来填充输入。