user3593826
user3593826

Reputation: 27

Building association for rails model

I have a user that has_one :company. I need to build the company's attributes via the strong parameters, but i'm running into a ActiveModel::ForbiddenAttributesError. My code looks like this:

    def create
     @user = User.new(permitted_user_params)
     @user.build_company(params[:user][:company_attributes])
    end

    def permitted_user_params
     params.require(:user).permit(:email, :first_name, :last_name, 
                              company_attributes: [:name, :bio])
    end

My company.rb looks like

class Company < ActiveRecord::Base
 belongs_to :user
end

My user.rb

class User < ActiveRecord::Base
 has_one :company
 accepts_nested_attributes_for :company
end

Any help is appreciated, thanks.

Upvotes: 0

Views: 33

Answers (1)

Taryn East
Taryn East

Reputation: 27747

So you shouldn't need to do this part:

 @user.build_company(params[:user][:company_attributes])

that part is implied in accepts_nested_attributes and it should do that for you, as long as you have you permit/require set up correctly (which you do).

Upvotes: 1

Related Questions