ActiveModel::MassAssignmentSecurity::Error in CustomersController#create (attr_accessible is set) - ruby-on-rails

In my controller, I've got error when create action and try create model [can't mass-assignment], but
in my spec, my test of mass-assignment model its pass!?!
My Model:
class Customer < ActiveRecord::Base
attr_accessible :doc, :doc_rg, :name, :birthday, :name_sec, :address, :state_id, :city_id, :district_id,
:customer_pj, :is_customer, :segment_id, :activity_id, :person_type, :person_id
belongs_to :person , :polymorphic => true, dependent: :destroy
has_many :histories
has_many :emails
def self.search(search)
if search
conditions = []
conditions << ['name LIKE ?', "%#{search}%"]
find(:all, :conditions => conditions)
else
find(:all)
end
end
end
I`ve tired set attr_accessible in controller too, in my randomized way.
the Controller:
class CustomersController < ApplicationController
include ActiveModel::MassAssignmentSecurity
attr_accessible :doc, :doc_rg, :name, :birthday, :name_sec, :address, :state_id, :city_id, :district_id, :customer_pj, :is_customer
autocomplete :business_segment, :name, :full => true
autocomplete :business_activity, :name, :full => true
[...]
end
The test, my passed test
describe "accessible attributes" do
it "should allow access to basics fields" do
expect do
#customer.save
end.should_not raise_error(ActiveModel::MassAssignmentSecurity::Error)
end
end
The error:
ActiveModel::MassAssignmentSecurity::Error in CustomersController#create
Can't mass-assign protected attributes: doc, doc_rg, name_sec, address, state_id, city_id, district_id, customer_pj, is_customer
https://github.com/megabga/crm
1.9.2p320
Rails 3.2
MacOS
pg

my bad, in my controller its setting an oldest class. Then old class don`t have attributes passing in parameters. Sorry!

Related

NoMethodError (undefined method `locked'

I get an error in my application on production envinronment at a random rate. When I restart the server the problem disappears for some time and then resurfaces.
This is the error
NoMethodError (undefined method `locked' for #<Class:0x00000006776a40>):
app/controllers/orders_controller.rb:29:in `rescue in new'
app/controllers/orders_controller.rb:29:in `new'
The Codesnipped looks like this:
#order.product_option = ProductOption.find_by_identifier(params[:product]) rescue ProductOption.first
For explanation. This snipped pre-selects the product option in the front-end.
The error occors in other areas and also related with the ProductOption model.
The model product_option looks like this:
class ProductOption < ActiveRecord::Base
attr_accessible :identifier, :price, :servings, :title
before_destroy :check_for_deps
has_many :users
has_many :orders
belongs_to :product
attr_accessible :product_id, :product, :price, :identifier, :servings, :color
validates_presence_of :identifier, :price, :product
validates_numericality_of :price, greater_than_or_equal_to: 1
validates_numericality_of :servings, greater_than_or_equal_to: 1
default_scope order('products.position, servings').includes(:product)
def title
I18n.t 'order_form.product_option_title',
recipe_count: self.product.recipe_count,
product_title: self.product.title,
servings: self.servings
end
def subtitle
self.product.subtitle
end
def pretty_price
'%.2f' % self.price
end
def check_for_deps
if users.count > 0
errors.add(:base, I18n.t('model.validation.product_has_still_objects_assigned'))
return false
end
if orders.count > 0
errors.add(:base, I18n.t('model.validation.product_has_still_objects_assigned'))
return false
end
end
end
This is product.rb:
class Product < ActiveRecord::Base
before_destroy :check_for_options
acts_as_list
translates :title, :subtitle, :description
active_admin_translates :title, :subtitle, :description do
validates_presence_of :title
end
attr_accessible :discount, :remarks, :title, :description, :subtitle, :product_options, :product_option_ids, :recipe_count
validates_presence_of :title
has_many :recipe_assignments
has_many :deliveries, through: :recipe_assignments
has_many :orders
has_many :product_options
default_scope order('position ASC')
private
def check_for_options
if product_options.count > 0
errors.add(:base, I18n.t('model.validation.product_has_still_objects_assigned'))
return false
end
end
end
I am using Rails v3.2.18
Troubleshooting
When I did some research I came accross this rails-issue #7421. But the issue was closed and declared as not being a bug.
According to #lifius i ran the following command:
culprit = :locked
ActiveRecord::Base.descendants.find {|e| e.singleton_methods.include?(culprit)}
# Result
Delivery(id: integer, delivery_date: date, remarks: text, created_at: datetime, updated_at: datetime, status: string)
You may execute the following:
Rails.application.eager_load!
ActiveRecord::Base.descendants.find {|e| e.singleton_methods.include?(:locked)}
in the rails console and see affected models.

Upgrading attr_accessible from Rails 3 to Rails 4

I'm trying to systematically upgrade from rails 3 to rails 4 and all of my 25 models are based on attr_accessor! So before getting into that can anyone provide me a simple example on how to do this. I've read the documentation and other topics but it's not clear on how to do it since this is my first upgrade Rodeo.
class Settings < ActiveRecord::Base
image_accessor :favicon
attr_accessible :company_name, :show_hot_jobs, :show_students, :subheading, :show_testimonials, :show_on_boarding, :max_concurrent_applications
attr_accessible :image_uid, :max_concurrent_application_groups
attr_accessible :primary_color, :white_color, :gray_color, :opacity, :locale, :lang_nl, :lang_fr, :lang_de, :lang_en, :privacy_page
attr_accessible :show_evp, :show_contact_person, :show_jobs_for_you
attr_accessible :favicon, :favicon_uid, :remove_favicon, :retained_favicon
attr_accessible :home_url, :show_correspondence, :show_appointment
attr_accessible :sliderone_uid, :slidertwo_uid, :sliderthree_uid, :sliderfour_uid, :sliderfive_uid
attr_accessible :sliderone_link, :slidertwo_link, :sliderthree_link, :sliderfour_link, :sliderfive_link
attr_accessible :sliderone_testoverview, :slidertwo_testoverview, :sliderthree_testoverview, :sliderfour_testoverview, :sliderfive_testoverview
attr_accessible :sliderone_page, :slidertwo_page, :sliderthree_page, :sliderfour_page, :sliderfive_page
validate :any_lang_present?
validates :max_concurrent_applications, :numericality => { :greater_than_equal_to => 1 }
validates :max_concurrent_application_groups, :numericality => { :greater_than_equal_to => 1 }
# Fav Icon Validation
validates_property :ext, of: :favicon, :in => ['ico', 'png', 'gif']
has_paper_trail
has_many :setting_translations, :foreign_key => :setting_id
accepts_nested_attributes_for :setting_translations, :allow_destroy => true, :reject_if => :all_blank
attr_accessible :setting_translations_attributes, :allow_destroy => true
translates :subheading, :company_name, :image_uid, :home_url, :sliderone_uid, :slidertwo_uid, :sliderthree_uid, :sliderfour_uid, :sliderfive_uid
translates :sliderone_link, :slidertwo_link, :sliderthree_link, :sliderfour_link, :sliderfive_link
translates :sliderone_testoverview, :slidertwo_testoverview, :sliderthree_testoverview, :sliderfour_testoverview, :sliderfive_testoverview
translates :sliderone_page, :slidertwo_page, :sliderthree_page, :sliderfour_page, :sliderfive_page
attr_accessible can be converted like so:
From
class Settings
attr_accessible :home_url
accepts_nested_attributes_for :setting_translations
end
class SettingTranslation
attr_accessible :etc
end
To
class SettingsController
def create
#settings = Settings.new(settings_params)
# ...
end
private
def settings_params
params.require(:settings).permit(
:home_url,
:setting_translations_attributes => [:id, :_destroy, :etc]
)
end
end
Note, you have to include :_destroy if you want to allow destroy on that model (:allow_destroy => true), and you have to include all attributes that should be accessible from any nested attributes. Though you remove attr_accessible when you've permitted, you do not remove accepts_nested_attributes_for.
Just remove attr_accessible from model. and add permit params according to need in controller.
like below :
class SupportTicketsController < ApplicationController
def create
#support_ticket = SupportTicket.create(house_params)
......
end
private
def house_params
params.require(:support_ticket).permit(:subject, :message, ....)
end
end
and if you don't want to make this much changes then add "protected_attributes" gem https://github.com/rails/protected_attributes in your gemfile And everything would work as before.

How to add data in refinerycms engine

Has anyone else run into a mass assignment error when trying to create a new piano?
ActiveModel::MassAssignmentSecurity::Error in Refinery::Pianos::Admin::PianosController#create
Can't mass-assign protected attributes: name, dimensions, manufactured_on(1i), manufactured_on(2i), manufactured_on(3i), upright, photo_id, description, position
If you open up your model file and put this in there you will have more success:
attr_accessible :dimensions, :manufactured_on, :upright, :photo_id, :description, :position
The model file should look like this:
module Refinery
module Pianos
class Piano < Refinery::Core::BaseModel
self.table_name = 'refinery_pianos'
attr_accessible :dimensions, :manufactured_on, :upright, :photo_id, :description, :position
acts_as_indexed :fields => [:dimensions, :description]
validates :dimensions, :presence => true, :uniqueness => true
belongs_to :photo, :class_name => '::Refinery::Image'
end
end
end
Hope that helps. I guess it's a bug in the version you're using but it's fixed in the Refinery CMS 2-0-stable branch.

How can I properly configure rails 3 nested attributes

I have 2 models. Member and Survey
member.rb as follows
Class Member < ActiveRecord::Base
has_one :survey, :dependent => :destroy
accepts_nested_attributes_for :survey
attr_accessible :fname,:lname, :address, :city, :state, :zip, :email, :phone, :phone_alt, :e_contact, :e_contact_phone, :physician, :physician_phone, :chiropractor, :chiropractor_phone, :password, :password_confirmation, :remember_me, :survey_attributes
end
survey.rb as follows
Class Survey < ActiveRecord::base
belongs_to :member
end
however, whenever I try to create the member with the survey attributes I receive
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: surveys
I am testing this via the console.
With a has_one association the accessible call should read:
attr_accessible :survey_attributes
The params you're posting need to be nested, like so:
params = { :member => { :name => 'Jack', :survey_attributes => { :attribute => 'value' } } }
In the form make sure that you're building the nested relationship correctly, ie. you must use:
= form_for #member do |f|
...
= f.fields_for :survey do |s|
...
If you have those things setup like so it should work. If this isn't catching your error then please show a log of what you're trying in the console and isn't working.
See #accepts_nested_attributes_for in the Rails API for more info.

creating a new associated object through build always sets some columns to nil in Rails

I have a simple one-to-many relationship between user and micropost as below. I tried to add a new column called stage to the Micropost model. when I try to build a new Micropost and save, the stage column is always automatically set to nil. I have tried create, build - doesn't matter, the stage field is always set to nil. I am baffled, please help!
$ rails console
Loading development environment (Rails 3.0.5)
>> User.first.microposts.create!( :stage => "p", :content => "test 6" )
=> #<Micropost id: 2, content: "test 6", stage: nil, user_id: 1, created_at: "2011-04-23 22:14:20", updated_at: "2011-04-23 22:14:20">
...
class Micropost < ActiveRecord::Base
attr_accessible :content, :stage
attr_accessor :stage
belongs_to :user
validates :content, :presence => true, :length => { :maximum => 140 }
validates :user_id, :presence => true
default_scope :order => 'microposts.created_at DESC'
scope :from_users_followed_by, lambda { |user| followed_by(user) }
private
def self.followed_by(user)
followed_ids = %( SELECT followed_id FROM relationships
WHERE follower_id = :user_id)
where "user_id IN (#{followed_ids}) OR user_id = :user_id",
{ :user_id => user }
end
end
...
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :password, :password_confirmation
has_many :microposts, :dependent => :destroy
end
You need to remove line:
attr_accessor :stage
Without it everything works fine. I think it's conflict between attr_accessor and attr_accessible.

Resources