【问题标题】:Rails 3 after_initialize to create a postRails 3 after_initialize 创建帖子
【发布时间】:2012-07-07 18:26:58
【问题描述】:

我正在尝试在 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

【问题讨论】:

  • 您希望在首次创建User 时创建一个虚拟帖子?使用这样的默认值不是方法。而是在 UserObserver 中创建帖子,并使用您想要的虚拟帖子的任何值。
  • 同意 Zabba,这应该是为了响应用户创建而不是精神创建。把它放在观察者api.rubyonrails.org/classes/ActiveRecord/Observer.html(或者不太正确的用户控制器创建方法)
  • 你们有没有使用 ActiveRecord Observer 的示例。这些例子有点挑战性。

标签: ruby-on-rails rails-activerecord


【解决方案1】:

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

迁移内部:

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

在 User 的 create 方法中

ethos = @user.ethos.build

感谢克里斯·杜辛的帮助!

【讨论】:

    【解决方案2】:

    只需使用回调方法“after_save”

    class Etho

    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
    

    【讨论】:

      猜你喜欢
      • 2011-06-21
      • 2011-11-09
      • 2012-04-26
      • 2012-06-17
      • 1970-01-01
      • 2021-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多