通过嵌套属性更新关联模型上的多个复选框茧宝石|导轨

时间:2017-03-26 21:42:19

标签: ruby-on-rails nested-attributes cocoon-gem

我有一个House模型,has_many house_rules

class House < ActiveRecord::Base
 has_many :house_rules, dependent: :destroy
 accepts_nested_attributes_for :house_rules, reject_if: :all_blank, allow_destroy: true
end

这是house_rule模型

class HouseRule < ActiveRecord::Base
 belongs_to :house
 enum rule_type: { predefined: 0, user_defined: 1 }
 enum allowed: { no: 0, yes: 1 }
end

以下是house_rules table

的其他列
create_table "house_rules", force: :cascade do |t|
    t.integer  "house_id"
    t.string   "rule"
    t.integer  "rule_type",  default: 1
    t.integer  "allowed",    default: 0
    t.datetime "created_at",             null: false
    t.datetime "updated_at",             null: false
end

我在数据库中保存了一些预定义的house_rules,默认情况下allowed列设置为0。例如:

<HouseRule id: 4, house_id: nil, rule: "Smoking allowed", rule_type: 0, allowed: 0, created_at: "2017-03-26 20:54:09", updated_at: "2017-03-26 20:54:09">

我希望在新的house_rules表单中将所有这些house作为check_box。像这样。 enter image description here

因此,当用户选中标签为“允许吸烟”的复选框时,会创建一条新记录,如此

<HouseRule id: 5, house_id: 1, rule: "Smoking allowed", rule_type: 1, allowed: 1, created_at: "2017-03-26 20:54:09", updated_at: "2017-03-26 20:54:09">

rule_type: 1 #user_defined rule
allowed: 1   #smoking is allowed

这是我的新house表格

<%= simple_form_for @house do |f| %>
<div id="house_rules">
  <%=  f.simple_fields_for :house_rules do |house_rule| %>
  <% HouseRule.predefined.each do |rule| %>
  <div>
    <%= house_rule.label :allowed, rule.rule %>
    <%= house_rule.check_box :allowed, {}, 'yes', 'no' %> 
  </div>
  <% end %>
  <% end %>
</div>
<% end %>

上面的代码按预期显示复选框,但无法按预期工作。有人可以指导我如何使这项工作?

另外,我在HousesController

中将这些列入白名单
house_rules_attributes: [:id, :allowed, :_destroy])

编辑:

这是表单为每个复选框生成的代码

<label for="house_house_rules_attributes_0_allowed">Smoking Allowed</label>
 <input name="house[house_rules_attributes][0][allowed]" type="hidden" value="0"><input type="checkbox" value="1" name="house[house_rules_attributes][0][allowed]" id="house_house_rules_attributes_0_allowed">

问题是,所有复选框的idname属性都相同,因此即使选中复选框,也只会检查第一个复选框。

正在为相关联的住宅创建新的house_rule记录,但allowed值仍为0,而不是1

这是我的HousesController new action

def new
 @house = House.find(params[:id])
 @house.house_rules.build
end

1 个答案:

答案 0 :(得分:1)

这不能正确呈现表单,因为您实际上并未迭代嵌套行,这就是所有行的id为0的原因。

相反,我会在house操作中为控制器中的new预先创建所有预定义规则。如下:

def new 
  @house = House.new 
  HouseRule.predefined.each do |hr|
    @house.house_rules.build(rule: hr.rule)
  end 
end 

在你看来,像往常一样迭代房屋规则:

<%=  f.simple_fields_for :house_rules do |house_rule| %>
  <%= house_rule.label :allowed, house_rule.object.rule %>
  <%= house_rule.check_box :allowed, {}, 'yes', 'no' %> 
</end>