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