实际上,为用户创建配置文件的最佳方法是什么
has_one :profile, dependent: :destroy
after_create :create_profil
def create_profile
@profile = Profile.create(user: self)
end
但个人资料必须包含其他信息,例如经验、教育、技能,... 所以我想知道最好的方法是什么,我想使用嵌套属性这将是一个很好的解决方案吗?
您应该访问有关创建关联的 rails 基础知识。
- 如果坚持为用户使用单个配置文件,则可以使用一对一关联。
检查以下链接:http://guides.rubyonrails.org/association_basics.html#choosing-between-belongs-to-and-has-one
我建议您将配置文件数据保留在用户模型中,因为以后访问该信息会更自然
user.skills = "some skills"
user.experience = "a lot of experience"
而不是轮廓模型
user.profile.skills = "some skills"
user.profile.experience = "a lot of experience"
但是要回答您的问题,最好的方法是创建一个具有一对一关系的配置文件模型(我假设您使用的是 rails 4)
rails g model profile field1:type field2:type user:references
,然后将关系添加到每个模型
models/user.rb
has_one :profile, :dependent => :destroy
models/profile.rb
belongs_to :user
对于嵌套属性,我建议您查看这个 railscast,它解释了如何使用它们,然后而不是自己创建,您应该使用茧宝石来使其更简单。
我希望它对:D有所帮助