我有一个模型User
。我想要一个函数,为每个用户记录设置属性emotion
等于happy
。
class User < ActiveRecord::Base
attr_accessor :emotion
def self.add_a_happy_emotion
users = User.all
users.each do |user|
user.emotion = "happy"
end
users
end
end
当我在控制台中调用> User.add_a_happy_emotion
时,用户没有任何emotion
属性。它们只具有默认的模型属性。如果在do循环中调用属性,是否会设置属性?或者这与attr_accessor有关吗?或者我可能错过了其他的东西?
答案 0 :(得分:1)
如果您使用Rails 4. User.all
将返回活动记录关系而不是数组。
因此,您必须修改代码才能获得用户更新的属性。
def self.add_a_happy_emotion
users = User.all
result_users = users.map do |user|
user.emotion = "happy"
user
end
result_users
end
答案 1 :(得分:0)
可能是它正在返回缓存的副本。这个怎么样
def self.add_a_happy_emotion
users = User.all
users.each do |user|
user.emotion = "happy"
end
end
答案 2 :(得分:0)
有2个问题:
1 - 您的 attr_accessor 正在覆盖Rails&#39;。你真的不需要它在Rails中。只需将模型的属性放在迁移中,您就可以了。
2 - 如果您修改用户对象并且不保存它们,则永远不会保留更改。您可以使用 update_attribute 来实现此目的。
所以你最终会得到类似的东西:
class User < ActiveRecord::Base
#no more attr_accessor here
def self.add_a_happy_emotion
users = User.all
users.each do |user|
user.update_attribute(:emotion, "happy") #this persists the entities to the DB
end
end
end