我有3个型号:
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][]。
发布于 2012-10-29 19:57:06
确保:heuristic_ids (虚拟)字段可访问:
attr_accessible :heuristic_ids # in the model. PLURAL!然后尝试在控制台中执行此操作(弹出一声以显示任何验证错误):
> Reference.create!("heuristic_ids"=>["", "2"])通过这种方式,您将获得更多关于为什么不保存此文件的信息。
发布于 2012-10-29 19:39:31
啊,我在最近的项目中遇到了同样的问题,我没有深入研究为什么"“会出现在params[:reference][:heuristic_ids] = params[:reference][:heuristic_ids].select{|x| x.to_i >0 }或params[:reference][:heuristic_ids].shift这样的控制器中,看看它对你有什么作用,然后检查一下。
保存"“id导致验证错误,
https://stackoverflow.com/questions/13120754
复制相似问题