ActiveModel::MassAssignmentSecurity::Error in ApiUsersController#create - ruby

I am not able to create new api_user. Everytime I try to create it I get
Can't mass-assign protected attributes: utf8, authenticity_token, api_user, commit, action, controller
here's my model api_user.rb
class ApiUser < ActiveRecord::Base
attr_accessible :api_key, :count, :email, :name, :organization
end
controller api_users_controller.rb
class ApiUsersController < ApplicationController
#skip_before_filter :verify_authenticity_token
def new
#api_user = ApiUser.new
end
def create
#api_user=ApiUser.create(params)
render :text=>"#{#api_user.id}"
end
def destroy
#api_user=ApiUser.find(params[:id])
#api_user.destroy
render :text=>"Deleted successfully"
end
end
I am using Ruby 1.9.2 and Rails 3.2.3

In order to create the ApiUser, you should use only the correct params:
#api_user=ApiUser.create(params[:api_user])
not all the paramshash

Related

Calling a Associated Controller Method Not Working

I have 3 models of User, Role and UserRole with their respective controllers as UsersController, RolesController and UserRolesController.
I have a method in the UserRoles controller which I would want to access through the Users controller but I keep having errors as explained below.
I have tried various means of even moving the method def self.add_roles_to_user(user, role) from the UsersRoles controller into the UserRole model and call it but I keep having the same error.
I have gone through lots of similar questions and various blogs, including those on this platform such as Calling a method from controller, and others but to no good results.
class UserRole < ApplicationRecord
# many-to-many association using join table with roles and user
belongs_to :user, inverse_of: :user_roles
belongs_to :role, optional: true, inverse_of: :user_roles
end
class User < ApplicationRecord
has_many :user_roles, inverse_of: :user
has_many :roles, through: :user_roles
end
class Role < ApplicationRecord
# table associations between role and user
has_many :user_roles, inverse_of: :role
has_many :users, through: :user_roles
end
class UserRolesController < ApplicationController
def self.add_roles_to_user(user, role)
if ! user.nil?
if role.length > 0
role.each do |sel_role|
#u_role = UserRole.new
#u_role.user_id = user_id
#u_role.role_id = sel_role.role_id
#u_role.save
end
end
end
end
end
class Users::RegistrationsController < Devise::RegistrationsController
def create_user
respond_to do |format|
if #user.save
# add roles
UserRoles.add_user_roles(params[:user], params[:role])
end
end
end
end
I am calling the add_uer_to_role method in the User controller when I am adding or creating a new user.
What I have noticed is that I keep getting different errors based on how I call the method.
For example, I expect to have no errors when I call the method like; UserRoles.add_roles_to_user(params[:user], params[:role]) but it gives the error NameError (uninitialized constant Users::RegistrationsController::UserRoles):
Hoping a good samaritan will come to my aid as soon as possible. Thanks in advance
If it is a common function, you can define it in application controller and call it. Else you can define in helper.
Please verify Calling a method from another controller
You can use that function as a module and use it:
# lib/common_stuff.rb
module CommonStuff
def common_thing
# code
end
end
# app/controllers/my_controller.rb
require 'common_stuff'
class MyController < ApplicationController
include CommonStuff
# has access to common_thing
end

Paperclip don't save on database

I am using the following Gems:
'paperclip'
'aws-sdk', '~> 2.3'
I would like to save images to S3, but am unable to get them to save.
model/user.rb
class User < ApplicationRecord
# This method associates the attribute ":avatar" with a file attachment
has_attached_file :avatar, styles: {
thumb: '100x100>',
square: '200x200#',
medium: '300x300>'
}
# Validate the attached image is image/jpg, image/png, etc
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
end
migration
class AddAvatarToUsers < ActiveRecord::Migration[5.1]
def self.up
add_attachment :users, :avatar
end
def self.down
remove_attachment :users, :avatar
end
end
controllers/users_controller.rb
class UsersController < ApplicationController
def edit
#user = User.find_by(id: params[:id])
end
def update
#user = User.find(params[:id])
if #user.update(user_params)
flash[:notice] = "Edit successfully"
redirect_to("/users/#{#user.id}")
end
end
private
def user_params
params.require(:user).permit(:avatar, :name, :email, :phone_number, :description, :college_name)
end
end
Why is the image avatar not being stored in the database?
Should I add any database columns? What should I do? I would appreciate any input to help me solve this problem.
Paperclip must be configured to use S3 to store the objects (images). It will store metadata associated with these in the database, but not the images.
See Paperclip Documentation
You will also need to set an access policy for your S3 bucket, and define on the User model how they are to be addressed from S3.

Can't mass-assign protected attributes attr_accessor and attr_accessible

in rails 2.3.11, I have below in model
attr_accessor :person_id
and in controller
#project.person_id = current_user.id
now, I am converting this in rails 3.2.11 and I am getting
Can't mass-assign protected attributes: person_id
so I changed in model, I removed :person_id from attr_accessor and add below line
attr_accessible :person_id
but I am uisng person_id in controller, here it is
#project.person_id = current_user.id
I am getting this now
NoMethodError in ProjectsController#create
undefined method `person_id=' for #<Project:0x19cc51a>
any idea or help, How can I fix this? How can I handle both attr_accessor & attr_accessible?
attr_accessor :person_id and attr_accessible :person_id are not the same.
attr_accessor is the Ruby method. In short its shortcut for methods:
def person_id
#person_id
end
def person_id=(value)
#person_id = value
end
attr_accessible is the Rails method. Which gets list of attributes allowed to be mass-assigned. You can read about here.
Thus in your case you need both of them.
attr_accessor :person_id
attr_accessible :person_id

Using Ability class in Rails Engine

I have a engine inside the lib folder named Support. In that folder, I have a Ticket controller.
I have created an ability class in the main app and I'm trying to manage all the models for the admin role. When I call the Tickets controller, it throws the error:
NameError in Support::TicketsController#index uninitialized constant Ticket
The app/model/ability.rb file is:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.role? == :admin
can :manage , :all
end
end
end
The lib/support/tickets_controller.rb file is:
module Support
class TicketsController < Support::ApplicationController
load_and_authorize_resource
respond_to :html, :xml, :json
def index
end
end
end
If the model class is namespaced differently than the controller, you will need to specify the :class option.
module Support
class TicketsController < ApplicationController
load_and_authorize_resource :class => Support::Ticket
end
end

"undefined method" for a rails model

I am using Devise with rails and i want to add a method "getAllComments", so i write this :
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :city, :newsletter_register, :birthday, :postal_code,
:address_complement, :address, :lastname, :firstname, :civility
has_many :hotels_comments
class << self # Class methods
def getAllComments
true
end
end
end
And in my controller :
def dashboard
#user = current_user
#comments = #user.getAllComments();
end
And when i go to my url, i got
undefined method `getAllComments' for #<User:0x00000008759718>
What i am doing wrong?
Thank you
Because getAllComments is a class method and you are attempting to access it as an instance method.
You either need to access it as:
User.getAllComments
or redefine it as an instance method:
class User < ActiveRecord::Base
#...
def getAllComments
true
end
end
def dashboard
#user = current_user
#comments = #user.getAllComments
end
As I can see, you make getAllComments as class method through addition it to eigenclass. And you try to call this method from instance.
Content of class << self means class method. It could be shortened as def self.getAllComments
You should call it User.getAllComments and not #user.getAllComments
The getAllComments() method that you wrote is a class method
So the correct way to call the methods is
#comments = User.getAllComments
But if you really want to scope the getAllComments to the current user, I recommend you write an instance method
class User < ActiveRecord::Base
..
def getAllComments
// comments implementation
end
So that way you can access the getAllComments method like so:
#user = current_user
#comments = #user.getAllComments

Resources