【问题标题】:How to call correctly methods from a model relating to other controllers?如何从与其他控制器相关的模型中正确调用方法?
【发布时间】:2010-11-23 20:54:44
【问题描述】:

在我的 Ruby on Rails 应用程序中,我想为配置文件创建一个新的配置文件和一个新的统计信息,所有这些都首先从用户模型调用相关方法,然后从配置文件模型调用。

所以……

...在我的用户模型(user.rb)中我有这个:

...

has_one :profile

...
before_save :inizialize_user
...

private

def inizialize_user
  @user_profile = Profile.new
  self.user_profile_id = @user_profile.id
end

...在我的个人资料模型 (profiles.rb) 我有这个:

...
belongs_to :user
...

before_save :inizialize_profile

private

def inizialize_profile
  @profile_statistic = ProfileStatistic.new
end

在第二个代码块中,在“before_save”中,它实例化了一个新的配置文件统计信息: “检查”@profile_statistic 生成一个新对象(正确!)

在第一个代码块中,在“before_save”中它不会实例化新的配置文件: “检查”@user_profile 结果为零(它必须是一个新的配置文件对象!)

最后一部分是我的问题。为什么会这样?

【问题讨论】:

    标签: ruby-on-rails-3 methods model controller


    【解决方案1】:

    当您调用Profile.new 时,它只会在内存中创建一个实例,它不会保存到数据库中,因此没有id 属性(即@user_profile.id 为nil)。

    我建议你更换

    @user_profile = Profile.new
    

    @user_profile = Profile.create
    

    create 将保存实例,然后@user_profile.id 不会为 nil。

    您可能还想使用before_create 回调(而不是before_save),否则每次保存模型时(例如在更新后)都会有新的用户配置文件。另外,你可能想拥有

    ProfileStatistic.create
    

    而不是

    ProfileStatistic.new
    

    【讨论】:

    • 我不明白为什么“ProfileStatistic.create”不起作用:似乎没有创建新的 Profile 对象。
    • ProfileStatistic.create 将记录保存到数据库中。因此,如果您的验证失败,它将无法正常工作。例如,如果您有一个“validates_presence_of :name”,您可以像这样 ProfileStatistic.create(:name => 'the name you want') 来创建它。确保创建所有验证通过的配置文件统计信息。您可以在控制台中使用“p = ProfileStatistic.create”对其进行测试。如果控制台返回“false”,请使用“p.errors”查看原因
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 2013-04-18
    相关资源
    最近更新 更多