Question

I have a model called DefaultCompany that has no controller, instead I create it through the companies_controller which calls the user.set_default_company (defined below) if they check the "default company" checkbox on the form.

Default company is a joining table of user_id and company_id.

class DefaultCompany < ActiveRecord::Base
  attr_accessible :company_id, :user_id
  belongs_to :company
  belongs_to :user
end

I keep getting the following error:

Can't mass-assign protected attributes: company, user 
app/models/user.rb:22:in `set_default_company'
app/controllers/companies_controller.rb:23:in `create'

I've set my user model to be able to accept nested attributes for DefaultCompany, like this

class User < ActiveRecord::Base
  has_one :default_company
  accepts_nested_attributes_for :default_company
  attr_accessible :default_company_attributes

  def set_default_company(company)
    exists = DefaultCompany.find(self.id)
    if exists
      exists.update_attributes(company: company)
    else 
      DefaultCompany.create(company: company, user: self)
    end
  end
end

And here is the create action for the companies_controller.rb

def create
@company = Company.new(params[:company])

if @company.save
  if params[:default_company]
    current_user.set_default_company @company.id
  end
  flash[:notice] = "Company was successfully created."
  Role.assign_creator(@company.id, current_user.id)
  redirect_to @company
else
  redirect_to new_company_path
  end
end

So I'm not sure what I need to add so that mass-assignment will pass, can anyone help me figure out / explain this?

Was it helpful?

Solution

I believe rails is strict about the naming in mass-assignment, so although you've whitelisted company_id and user_id, you have not whitelisted company and user.

Try changing the assignment in set_default_company to:

if exists
  exists.update_attributes(company_id: company.id)
else 
  DefaultCompany.create(company_id: company.id, user_id: self.id)
end

OTHER TIPS

You can either change the attr_accessible attributes on Company to :user and :company or set :company_id and :user_id in your set_default_company method call.

Edit:

exists = DefaultCompany.find(self.id)

This seems to be wrong according to your logic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top