在 Rails 2.3.8 中,如果我在验证中循环甚至检查 habtm 关联,则在对accepts_nested_attributes_for 关联进行验证时遇到问题,课程已加载并且任何更新都丢失了。例如,我有以下架构:
ActiveRecord::Schema.define(:version => 20100829151836) do
create_table "attendees", :force => true do |t|
t.integer "lesson_set_id"
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "lesson_sets", :force => true do |t|
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "lesson_sets_lessons", :id => false, :force => true do |t|
t.integer "lesson_id"
t.integer "lesson_set_id"
end
create_table "lessons", :force => true do |t|
t.integer "activity_id"
t.integer "limit"
t.datetime "created_at"
t.datetime "updated_at"
end
end
以及以下型号:
class Attendee < ActiveRecord::Base
belongs_to :lesson_sets
end
class Lesson < ActiveRecord::Base
has_and_belongs_to_many :lesson_sets
end
class LessonSet < ActiveRecord::Base
has_and_belongs_to_many :lessons
has_many :attendees
accepts_nested_attributes_for :lessons
validate do |lesson_set|
lesson_set.lessons.each do |l|
if l.limit < attendees.count
self.errors.add_to_base("Sorry only #{l.limit} people allowed on lesson")
end
end
end
end
如果我调用以下内容:
>> ls = LessonSet.first
=> #<LessonSet id: 1, created_at: "2010-08-29 07:50:23", updated_
at: "2010-08-29 07:50:23">
>> Lesson.last
=> #<Lesson id: 1, activity_id: 29, created_at: "2010-08-29 07:57:13", updated_a
t: "2010-08-29 17:04:34", limit: 5>
params = {"lessons_attributes"=>{"0"=>{"activity_id"=>"3", "id"=>"1", "_destroy"=>""}}, "id"=>"1"}
=> {"id"=>"1", "lessons_attributes"=>{"0"=>{"activity_id"=>"3", "id"=>"1", "_des
troy"=>""}}}
>> ls.update_attributes(params)
=> true
>> Lesson.last
=> #<Lesson id: 1, activity_id: 29, created_at: "2010-08-29 07:57:13", updated_a
t: "2010-08-29 17:04:34", limit: 5>
>> params = {"lessons_attributes"=>{"0"=>{"activity_id"=>"29", "id"=>"1", "_de>
=> {"id"=>"1", "lessons_attributes"=>{"0"=>{"activity_id"=>"29", "id"=>"1", "_de
stroy"=>""}}}
>> ls.update_attributes(params)
=> true
<y_id"=>"3", "id"=>"1", "_destroy"=>""}}, "id"=>"1"}
=> {"id"=>"1", "lessons_attributes"=>{"0"=>{"activity_id"=>"3", "id"=>"1", "_des
troy"=>""}}}
>> Lesson.last
=> #<Lesson id: 1, activity_id: 29, created_at: "2010-08-29 07:57:13", updated_a
t: "2010-08-29 17:04:34", limit: 5>
>> ls.update_attributes(params)
=> true
>> Lesson.last
=> #<Lesson id: 1, activity_id: 3, created_at: "2010-08-29 07:57:13", updated_at
: "2010-08-29 17:13:36", limit: 5>
这基本上是:
最后一课以 29 的活动ID 开始,在课程
集上调用 update_attributes 尝试将活动 ID 设置为 3
,它返回 true 但是当我们查看最后一课时它没有改变
,然后将活动 ID 设置为 29,即. 同样,调用 update_attributes
activity_id 仍然是 29
,但随后再次调用尝试将其设置为 3
,这一次它更新了课程。???
我的代码有问题吗,这对我来说似乎很奇怪,我在网上找不到任何类似的东西。
想我要去拍头的时刻了!