我正在开发一款计算口粮的应用。每种口粮都有很多种,每种口粮都属于口粮和饲料。我希望用户通过一次提交更新属于口粮的ration_items的数量,因此我在编辑口粮页面上创建了一个嵌套表格。
具有属于特定比率的ration_items的表格如下所示:
<%= form_for @ration do |f| %>
<table class="table table-striped">
<thead>
<tr>
<th>Quantity</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<% @ration.ration_items.each do |ration_item| %>
<%= render 'ration_item_row', feedstuff: ration_item.feedstuff, ration_item: ration_item, f: f %>
<% end %>
</tbody>
</table>
<%= f.submit %>
<% end %>
具有ration_item行的部分:
<%= f.fields_for ration_item do |r| %>
<tr>
<td><%= r.number_field :quantity, value: ration_item.quantity %></td>
<td><%= feedstuff.name %></td>
<td><%= link_to "", ration_item, method: :delete, class: "glyphicon glyphicon-trash", data: { toggle:'tooltip' }, title: 'Delete', data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
我在口粮控制器中添加了强力参数:
def ration_params
params.require(:ration).permit(:name, :user_id, ration_items_attributes: [:id, :quantity, :feedstuff_id])
end
现在,当我更改ration_item数量并提交时,它不会保存数量,而只会重定向到编辑页面。服务器输出如下:
Started PATCH "/rations/4" for 127.0.0.1 at 2015-08-18 16:11:05 +0200
Processing by RationsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"HeG3ffOcUJUY68ggiruE1pDReo8X5ftr4YBgBswGMJzQ+cOF3GlCcQHm3Kd349WTDkGzOwUtEEm2Ur9DpKGGPw==", "ration"=>{"ration_item"=>{"quantity"=>"500"}}, "commit"=>"Ration bewaren", "id"=>"4"}
Ration Load (0.2ms) SELECT "rations".* FROM "rations" WHERE "rations"."id" = ? LIMIT 1 [["id", 4]]
Unpermitted parameter: ration_item
(0.1ms) begin transaction
(0.1ms) commit transaction
Redirected to http://localhost:3000/rations/4/edit
Completed 302 Found in 6ms (ActiveRecord: 0.3ms)
关于如何让我的工作得到高度赞赏的任何想法!
ration.rb:
class Ration < ActiveRecord::Base
belongs_to :user
has_many :ration_items, dependent: :destroy
validates :name, presence: true
validates :user_id, presence: true
accepts_nested_attributes_for :ration_items
def to_s
name
end
end
ration_item.rb:
class RationItem < ActiveRecord::Base
belongs_to :feedstuff
belongs_to :ration
validates :feedstuff_id, presence: true
validates :quantity, presence: true
end
feedstuff.rb:
class Feedstuff < ActiveRecord::Base
validates :user_id, presence: true
validates :name, presence: true, length: {maximum: 20}, uniqueness: true
belongs_to :user
has_many :ration_items
def to_s
name
end
end