ruby-on-railsruby-on-rails-4update-attributes

Rails 4: update_attributes with different role


In rails 3 we could use update_attributes as below

@customer.update_attributes(params[:customer], :as => :default) 
or
@customer.update_attributes(params[:customer], :as => :admin)

and our attributes accessible would be defined as

attr_accessible :fname, :lname, :as => [:default, :admin]
attr_accessible :status, :as => [:admin]

But in rails 4, update_attributes does not accept second parameter. So how can I convert the above code to work in rails 4?

I tried something like this

  @customer.update_attributes(customer_params)

private
  def customer_params
    params.require(:customer).permit(:fname, :lname, :status )
  end 

But I don't know how to pass the role in rails 4 while updating attributes. I can not do something like this.

  @customer.update_attributes(customer_params, :as => :admin)

This is not allowed in rails 4. So how can I do similar thing in rails 4?


Solution

  • Have a look at strong parameters. The permitted attributes should be determined in the controller not the model

    http://edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters

    For example the controller would have

    def customer_params
       if current_user.admin?
         params.require(:customer).permit(:fname, :lname, :status)
       else
         params.require(:customer).permit(:fname, :lname)
       end
    end
    
    def update
      @customer.update_attributes(customer_params)
      ...
    end