0

我有 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][]

4

2 回答 2

1

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

attr_accessible :heuristic_ids # in the model. PLURAL!

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

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

通过这种方式,您将获得有关为什么没有保存的更多信息。

于 2012-10-29T11:57:05.743 回答
0

啊,我最近的一个项目也遇到了同样的问题,我没有深入研究为什么“”会像控制器一样进入控制器,params[:reference][:heuristic_ids] = params[:reference][:heuristic_ids].select{|x| x.to_i >0 } 或者只是 params[:reference][:heuristic_ids].shift 看看它对你有用并检查。

保存 "" id 导致验证错误,

于 2012-10-29T11:39:31.063 回答