如何从与其他控制器相关的模型中正确调用方法?
在我的 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 结果为零(它必须是一个新的配置文件对象!)
最后一部分是我的问题。为什么会发生这种情况?
In my Ruby on Rails application I want to create a new profile and a new statistic for profile, all calling first the related method from the user model, and then from the profile model.
So...
... in my user model (user.rb) I have this:
...
has_one :profile
...
before_save :inizialize_user
...
private
def inizialize_user
@user_profile = Profile.new
self.user_profile_id = @user_profile.id
end
... in my profile model (profiles.rb) I have this:
...
belongs_to :user
...
before_save :inizialize_profile
private
def inizialize_profile
@profile_statistic = ProfileStatistic.new
end
In the second block of code, on the "before_save" it instantiates a new profile statistic:
"inspecting" @profile_statistic results a new object (correct!)
In the first block of code, on the "before_save" it doesn't instantiate a new profile:
"inspecting" the @user_profile results nil (it must be a new profile object!)
The last part is my problem. Why it happens?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您调用
Profile.new
时,它仅在内存中创建一个实例,不会保存到数据库中,因此没有id
属性(即 @user_profile .id 为零)。我建议您替换
为
create
将保存实例,然后@user_profile.id将不会为零。您可能还想使用
before_create
回调(而不是before_save
),否则每次保存模型时(例如更新后)都会有新的用户配置文件。另外,您可能想要而不是
When you call
Profile.new
, it only creates an instance in memory, it isn't saved to the database and therefore doesn't have anid
attribute (i.e. @user_profile.id is nil).I suggest you replace
with
create
will save the instance and then @user_profile.id will not be nil.You probably also wan to use
before_create
callbacks (notbefore_save
), or you'll have new user profiles every time you save the model (e.g. after udpating). Also, you probably want to haveinstead of