在这个例子中,我创建了一个user
没有profile
,然后稍后创建一个profile
对于该用户。我尝试使用构建has_one
协会但是爆炸了。我看到这个工作的唯一方法是使用has_many
. The user
应该最多只有一个profile
.
我一直在尝试这个。我有:
class User < ActiveRecord::Base
has_one :profile
end
class Profile < ActiveRecord::Base
belongs_to :user
end
但是当我这样做时:
user.build_profile
我收到错误:
ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'profiles.user_id' in 'where clause': SELECT * FROM `profiles` WHERE (`profiles`.user_id = 4) LIMIT 1
Rails 有没有办法实现 0 或 1 关联?
The build
方法签名不同has_one
and has_many
协会。
class User < ActiveRecord::Base
has_one :profile
has_many :messages
end
构建语法为has_many
协会:
user.messages.build
构建语法为has_one
协会:
user.build_profile # this will work
user.profile.build # this will throw error
阅读has_one
协会文档更多细节。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)