question
has_many kpi
到kpiquestions
:
class Question < ActiveRecord::Base
has_many :kpiquestions, dependent: :destroy
has_many :kpis, through: :kpiquestions
end
class Kpi < ActiveRecord::Base
has_many :kpiquestions, dependent: :destroy
has_many :questions, through: :kpiquestions
end
class Kpiquestion < ActiveRecord::Base
belongs_to :kpi
belongs_to :question
end
现在我有一个有效的question
表单,我可以使用复选框添加KPI:
= form_for @question do |f|
= render "layouts/form_messages", target: @question
.form-group
= f.label "Name"
= f.text_field :name
.form-group
= f.label "KPI's"
%ul
= hidden_field_tag "question[kpi_ids][]", nil
- @kpis.each do |kpi|
%li.checkbox
= check_box_tag "question[kpi_ids][]", kpi.id, @question.kpi_ids.include?(kpi.id), "data-category" => kpi.id
= kpi.name
.form-group
= f.submit(class: 'btn btn-default', value: "Save")
但是联接表kpiquestion
有一个额外的属性weight
。此属性也应添加到表单中,并带有text_field_tag
。像这样:
= text_field_tag "question[kpi_ids][:weight]", kpi.weight, @question.kpi_ids.include?(kpi.id), "data-category" => kpi.weight
显然这不起作用,因为它现在返回一个错误,指出kpi
没有名为weight
的属性。那么如何将此属性添加到表单中呢?
答案 0 :(得分:1)
一种方法是将整个form_for变成一个form_tag,传递给相关控制器中的post请求,然后唯一限制你可以传递的参数就是你选择允许控制器的参数-侧。显然这违反惯例,但对于这样的情况,它很有用。
以下是代码将更改为:
= form_tag question_index_path, :method => :post do
= render "layouts/form_messages", target: @question *
.form-group
= label_tag "Name"
= text_field_tag :name
.form-group
=label_tag :weight
=text_field_tag :weight
.form-group
=label_tag "KPI's"
= hidden_field_tag "question[kpi_ids][]", nil
- @kpis.each do |kpi|
%li.checkbox
= check_box_tag "question[kpi_ids][]", kpi.id, @question.kpi_ids.include?(kpi.id), "data-category" => kpi.id
= kpi.name
.form-group
=submit_tag("Save", class: btn btn-default)