How to db:seed a model and all its nested models?

前端 未结 1 1980
情歌与酒
情歌与酒 2020-12-30 15:14

I have these classes:

class User
  has_one :user_profile
  accepts_nested_attributes_for :user_profile
  attr_accessible :email, :password, :password_confirm         


        
相关标签:
1条回答
  • 2020-12-30 16:20

    Your user model needs to be setup to accept nested attributes via accepts_nested_attributes

    See the Rails documentation for more info and examples: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

    Edit: Also you might want to consider using has_one :contact, :through => :user_profile which would allow you to access the contact like this: @contact = User.first.contact.

    Edit 2: After playing around in rails c the best solution I can find is this:

    @c = Contact.new(#all of the information)
    @up = UserProfile.new(#all of the information, :contact => @c)
    User.create(#all of the info, :user_profile => @up)
    

    Edit 3: See the question for a better solution.

    0 讨论(0)
提交回复
热议问题