0

我试图在 Rails 3 中使用 after_initialize 来自动构建某人的第一篇文章。我在模型中设置了默认值,但我希望一旦创建用户,它就会构建他们的第一个帖子。因此,他们将有一个 ID 为 1 的 Post 条目,而不只是 default_values。

模型:

class Etho < ActiveRecord::Base
belongs_to :user
attr_accessible :word_one, :word_two, :word_three, :word_four, :tagline
after_initialize :default_values

private
 def default_values
  self.word_one   ||= "Adventagious"
  self.word_two   ||= "Funny"
  self.word_three ||= "Multidisciplined"
  self.tagline    ||= "Shares the same visions as JFK. Wants to see the world fortune in prosperity."
 end

end
4

2 回答 2

0

弄清楚了。我忘了我可以在控制器内部构建。所以现在我在迁移中有一个 :default ,然后在用户创建方法上进行构建。

迁移内部:

add_column :ethos, :tagline, :text, :default => 'Shares a birthday with JFK. Believes in prosperty amongst humans.'

在 User 的 create 方法中

ethos = @user.ethos.build

感谢克里斯杜辛的帮助!

于 2012-07-08T16:30:37.803 回答
0

只需使用回调方法“after_save”

class Etho < ActiveRecord::Base belongs_to :user attr_accessible :word_one, :word_two, :word_three, :word_four, :tagline after_save :default_values

private
 def default_values
  self.word_one   ||= "Adventagious"
  self.word_two   ||= "Funny"
  self.word_three ||= "Multidisciplined"
  self.tagline    ||= "Shares the same visions as JFK. Wants to see the world fortune in prosperity."
 end

end
于 2012-07-14T11:59:09.377 回答