I have 3x models:
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
A join table:
class CreateFootnotes < ActiveRecord::Migration
def change
create_table :footnotes do |t|
t.integer :heuristic_id
t.integer :reference_id
t.timestamps
end
end
end
A form called from the new reference view:
= 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'
A references controller:
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
When you go to the new reference view, select a heuristic and click Save, I expect this to associate the selected heuristic with the reference, but when you drop into rails console you can see that it has not:
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 >
Why is this?
Thanks,
Steven.
BTW, I expected the reference[heuristic_ids][] to dynamically generate the name of each checkbox, but instead the name of each checkbox is the same: reference[heuristic_ids][].
Ensure that the
:heuristic_ids(virtual) field is accessible:Then try to do it in the console (with a bang to show any validation error):
this way you’ll get more information about WHY this doesn’t get saved.