0

有模型

Class ModelA < ActiveRecord::Base
  has_many :apples
  before_save :include_prime_apple_in_apples
  has_one :prime_apple


 def include_prime_apple_in_apples
     self.apple_ids << prime_apple_1.id
 end
end

l=ModelA.new(:apple_ids => [ "ap_1_id", "ap_2_id"],:prime_apple => prime_apple_1)
l.save
l.apple_ids.should include(prime_apple_1.id) # this doesnt seem to work

如何更改为关联传递的参数?

4

1 回答 1

0

那里有问题,但要回答您的问题:AFAIK,您只能分配给“other_ids”。您也可以直接推送到 has_many 关系:

self.apple_ids = self.apple_ids + [prime_apple_1.id]

或者

self.apples << prime_apple_1

您在 Apple 模型中设置了不同的 foreign_key 吗?has many will do a select * from apples where modela_id = X has one will do a select * from apples where modela_id = X limit 1 这意味着无论您在 prime_apple 访问器上设置什么,您都将获得第一个 Apple 记录。 ..

于 2012-05-18T19:33:34.647 回答