Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 无法从Rails中的关联模型获取值_Ruby On Rails_Ruby_Ruby On Rails 3_Devise_Mongoid - Fatal编程技术网

Ruby on rails 无法从Rails中的关联模型获取值

Ruby on rails 无法从Rails中的关联模型获取值,ruby-on-rails,ruby,ruby-on-rails-3,devise,mongoid,Ruby On Rails,Ruby,Ruby On Rails 3,Devise,Mongoid,正在使用的相关项目:Rails 3.2、Mongoid和Desive 我有以下两种型号: class User include Mongoid::Document include Mongoid::Timestamps has_one :profile, autosave: true, dependent: :delete field :account_level end class Profile include Mongoid::Document

正在使用的相关项目:Rails 3.2、Mongoid和Desive

我有以下两种型号:

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
我的应用程序设置为,成功注册帐户(用户)后,该用户将自动重定向以创建新的配置文件<代码>帐户级别是根据应用程序中的某些其他逻辑自动定义的

我希望根据用户模型的
帐户级别
自动填充
显示位置
的值

我试过各种方法让它工作,但我似乎能找到它


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

正如人们在评论中所说,使用回调:

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" 

在模型上保存前使用
,或在创建前使用
过滤器。我已经这样做了,但关联尚未创建。当我尝试运行
self.position\u order=profile.user.account\u level
时,它会抛出一个错误,因为尚未创建用户与配置文件的关联。然后,在保存后尝试和
或在创建后尝试
筛选。尝试…两者都不起作用。这对我来说毫无意义。这就是为什么我认为我一定是做错了什么。谢谢你的回答,德力诺。这与我尝试做的非常相似,但我仍然遇到了与nil:NilClass
相同的错误
未定义方法
account\u level'。它似乎没有在DB中创建并存储概要文件(这意味着它没有与用户关联),这就是它抛出错误的原因。如果我在保存后使用
过滤器,则会在数据库中创建一个配置文件,但尚未与用户关联-因此仍然返回相同的错误。有什么想法吗?我能想到的唯一一件事可能与mongoid创建/保存属于另一个模型的模型的方式有关。一旦配置文件被保存(用户实际点击表单上的保存配置文件),我就可以在上面调用
self.user.account\u level
。很抱歉,我需要查看完整的代码以获得帮助。您在何处以及如何创建用户和配置文件?