1

I have a app working great on Rails 4.0.3 Today when I try to upgrade to Rails 4.2.0, error happened with the code below:

    def self.create_comp(comp)
        c= Competition.new(comp[:competition])
        # add activities
        comp[:activities].each do |act|
            c.activities.new(act)
        end

        c.save!
        c
    end

And error message:

ActiveModel::ForbiddenAttributesError (ActiveModel::ForbiddenAttributesError):

What this function does is to save a competition with its associated activities in transaction.

I have the following line defined as association:

has_many :activities, autosave: true

So what has been changed in Rails 4.2 to make it throw this exception?

fuyi
  • 2,085
  • 3
  • 18
  • 38
  • http://stackoverflow.com/questions/17450185/forbidden-attributes-error-in-rails-4-when-encountering-a-situation-where-one-wo – pierallard Jan 21 '15 at 14:33

1 Answers1

0

@xiaopang, Rails 4.2 allow only strong parameters so you can define a private method where you have to permit model level attributes along with associated attributes in such a way

def method
  params.require(:competition).permit!.tap do |while_listed|
    while_listed[:activities] = params[:activities]
  end
end

Now Pass this private method while calling the class method (create_comp).

May this can resolve your problem.

You have one more way to resolve your issue like -- Define a private method in your controller and send this method name as a parameter.

def activities_params
  params.require(:activities).permit!
end

This will allow to create the associated model object.

jelder
  • 1,673
  • 1
  • 16
  • 17
Chitra
  • 1,096
  • 2
  • 8
  • 26
  • params.require(:competition).permit! works for my case. but this leaves the strong parameter in no use, right? – fuyi Mar 05 '15 at 10:27
  • @xiaopang, No this does not leave the strong parameter. To whitelist an entire hash of parameters, the permit! method can be used. – Chitra Mar 07 '15 at 04:46