简体   繁体   中英

Rails 4.2 ActiveModel::ForbiddenAttributesError when saving model with association

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?

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM