[英]Rails has_many association changes into parent model dont reflect?
For example, i have this: 例如,我有这个:
class Family < ActiveRecord::Base
:has_many :members
def aging(date)
members.find_all_by_birthday(date).each do |m|
m.age = m.age+1
# i dont want to put a m.save here
end
end
# some validations
end
@family = Family.first
@family.aging("2012-01-04")
@family.members.each do |m|
puts m.age
end
# it still the old age
I would like to use @family.save after calling aging method but it seems to not work that way, i would like to save this only if all validations met. 我想在调用老化方法后使用@ family.save,但它似乎无法正常工作,我想仅在满足所有验证条件的情况下保存它。 This is just an example to simplify what i need 这只是一个简化我需要的例子
The members.find_all_by_birthday(date)
does a separate query to return you a collection of members rather than fetching all members for the family into the association and then reducing it to the ones that have the corresponding birthday. members.find_all_by_birthday(date)
进行单独的查询,以向您返回成员集合,而不是将该家庭的所有成员提取到关联中,然后将其减少为具有相应生日的成员。
You can do: 你可以做:
members.select { |m| m.birthday == date }.each do |m|
m.age = m.age + 1
end
Which will modify the members in place. 这将修改成员到位。 It has the disadvantage of fetching them all from the database which the find_all_by_birthday
doesn't as it just fetches the ones you want. 它的缺点是无法从find_all_by_birthday
所获取的数据库中全部获取它们,因为它只是获取您想要的数据库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.