为什么不是我的“has_many:through”复选框更新我的第三个模型?

时间:2012-10-29 11:29:12

标签: ruby-on-rails forms associations haml

我有3x型号:

class Heuristic < ActiveRecord::Base
  has_many :footnotes
  has_many :references, :through => :footnotes
end

class Reference < ActiveRecord::Base
  has_many :footnotes
  has_many :heuristics, :through => :footnotes
end

class Footnote < ActiveRecord::Base
  belongs_to :reference
  belongs_to :heuristic
end

联接表:

class CreateFootnotes < ActiveRecord::Migration
  def change
    create_table :footnotes do |t|
      t.integer :heuristic_id
      t.integer :reference_id
      t.timestamps
    end
  end
end

从新参考视图调用的表单:

= form_for @reference do |f|
  .field
    = hidden_field_tag "reference[heuristic_ids][]", nil
    - @heuristics.each do |heuristic|
      = label_tag dom_id(heuristic), heuristic.description
      = check_box_tag "reference[heuristic_ids][]", heuristic.id, @reference.heuristics.include?(heuristic), id: dom_id(heuristic)
  .actions
    = f.submit 'Save'

参考控制器:

  def new
    @reference = Reference.new
    @heuristics = Heuristic.all
    respond_to do |format|
      format.html # new.html.erb
    end
  end

  def create
    @reference = Reference.new(params[:reference])
    respond_to do |format|
      if @reference.save
        format.html { redirect_to references_path, notice: 'Reference was successfully created.' }
      else
        format.html { render action: "new" }
      end
    end
  end

当您转到新的参考视图时,选择一个启发式并单击“保存”,我希望这会将选定的启发式与引用相关联,但是当您进入rails控制台时,您可以看到它没有:

ref = Reference.last
  Reference Load (0.9ms)  SELECT "references".* FROM "references" ORDER BY "references"."id" DESC LIMIT 1
+----+-----+----------+---------+-----------+-------------+
| id |  created_at              | updated_at              |
+----+-----+----------+---------+-----------+-------------+
| 2  |  2012-10-29 11:21:24 UTC | 2012-10-29 11:21:24 UTC |
+----+-----+----------+---------+-----------+-------------+
1 row in set
1.9.2p318 :002 > ref.heuristics
  Heuristic Load (1.0ms)  SELECT "heuristics".* FROM "heuristics" INNER JOIN "footnotes" ON "heuristics"."id" = "footnotes"."heuristic_id" WHERE "footnotes"."reference_id" = 2
 => [] 
1.9.2p318 :003 > Footnote.all
  Footnote Load (0.4ms)  SELECT "footnotes".* FROM "footnotes" 
 => [] 
1.9.2p318 :004 > 

为什么会这样?

谢谢,

史蒂芬。

顺便说一句,我希望reference[heuristic_ids][]动态生成每个复选框的名称,但每个复选框的名称都相同:reference[heuristic_ids][]

2 个答案:

答案 0 :(得分:1)

确保可以访问:heuristic_ids(虚拟)字段:

attr_accessible :heuristic_ids # in the model. PLURAL!

然后尝试在控制台中执行此操作(显示任何验证错误):

> Reference.create!("heuristic_ids"=>["", "2"])

通过这种方式,您可以获得有关为何无法保存的更多信息。

答案 1 :(得分:0)

啊我和我最近的一个项目有同样的问题,我没有深入研究为什么“”即将到来 在像params[:reference][:heuristic_ids] = params[:reference][:heuristic_ids].select{|x| x.to_i >0 }这样的控制器中  或者只是params[:reference][:heuristic_ids].shift看看它适用于你的任何东西并检查。

保存“”id会导致验证错误,