【问题标题】:Not able to get value from associate model in Rails无法从 Rails 中的关联模型中获取价值
【发布时间】:2014-04-03 18:42:01
【问题描述】:

正在使用的相关项目:Rails 3.2、Mongoid 和设计。

我有以下两种型号:

class User
    include Mongoid::Document
    include Mongoid::Timestamps
    has_one :profile, autosave: true, dependent: :delete
    field :account_level
end


class Profile
    include Mongoid::Document
    include Mongoid::Timestamps
    belongs_to :user
    field :display_position
end

我的应用程序已设置,因此在成功注册帐户(用户)后,此人会自动重定向以创建新的个人资料。 account_level 是根据应用中的一些其他逻辑自动定义的。

我希望根据 User 模型的 account_level 自动填充 display_position 的值。

我已经尝试了各种方法来让它工作,但我似乎可以弄明白。

实现这一目标的最佳方法是什么?

【问题讨论】:

  • 在您的模型上使用 before_savebefore_create 过滤器。
  • 我已经完成了,但关联已创建。当我尝试运行 self.position_order = profile.user.account_level 时,它会引发错误,因为尚未使用配置文件创建用户关联。
  • 然后尝试after_saveafter_create 过滤。
  • 试过了...都不行。这对我来说没有意义。这就是为什么我认为我一定在做一些根本错误的事情。

标签: ruby-on-rails ruby ruby-on-rails-3 devise mongoid


【解决方案1】:

正如人们在 cmets 中所说,为此使用回调:

class User
    include Mongoid::Document
    include Mongoid::Timestamps
    has_one :profile, autosave: true, dependent: :delete
    field :account_level
end


class Profile
    include Mongoid::Document
    include Mongoid::Timestamps
    belongs_to :user
    field :display_position

    before_create do
      self.display_position = self.user.account_level
    end
end

然后在控制台就可以查看了:

user = User.create( account_level: 'hello')
profile = Profile.create( user: user )
profile.display_position
 => "hello" 

【讨论】:

  • 感谢您的回复,Drinor。这与我尝试做的非常相似,但我仍然遇到相同的错误undefined method account_level' for nil:NilClass. It doesn't seem to have created and stored the profile in the DB (which means it's not associated with a user) which is why it's throwing the error. If I use the after_save`过滤器在数据库中创建了一个配置文件但与用户尚未 - 因此仍然返回相同的错误。关于发生了什么的任何想法?
  • 我唯一能想到的可能与 mongoid 创建/保存 belong_to 另一个模型的模型的方式有关。一旦配置文件被保存(用户实际上在表单上点击保存配置文件),我就可以在上面调用self.user.account_level
  • 抱歉,我需要查看完整的代码来帮助您。您在哪里以及如何创建用户和个人资料?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多