I have a User class defined like this
class User
end
And I have sublassed this to create an Owner class and created a has_one relationship with another Company class
class Owner < User
has_one :company
end
class Company
belongs_to :owner
end
In my Users controller when creating a new User I want to accomplish the following:
- Create a new User
- Create a new Company
- Associate the User with the Company (as the Owner i.e. company.owner_id)
I can accomplish this with the following code (simplified for brevity)
def create
@user = User.new(params[:user])
@company = Company.new(params[:company])
if @user.save
@company.owner_id = @user.id
@company.save
...
Now, this just feels ugly to me, but I can’t seem to get the whole build_asociation process to work as expected (yes, fields are there in both dev and test).
What should I be doing here?
If you need to create
OwnerandCompanyat the same time, I suggest you useaccepts_nested_attributes_forinOwner. Here’s the code:Then in your controller you can do something like this:
For complete reference, please take a look at Active Record Nested Attributes and the view helper fields_for