在本例中,我创建了一个不带profile
的user
,然后为该用户创建了一个profile
。我尝试将build与has_one
关联一起使用,但是失败了。我认为唯一有效的方法就是使用has_many
。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的关联?
发布于 2010-03-19 05:00:38
has_one
和has_many
关联的build
方法签名是不同的。
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
关联documentation。
发布于 2010-03-19 04:45:14
它应该是一个has_one
。如果build
不工作,您可以直接使用new
ModelName.new( :owner => @owner )
等同于
@owner.model_names.build
https://stackoverflow.com/questions/2472982
复制相似问题