iam working in rails 3.while trying to creating a user i am getting
cant mass assign the protected attributes error
I included following gems in the gemfile
gem 'authlogic'
gem 'gemcutter'
and run bundle install in rails console
then create a a user model and add the required authlogic columns to the migration.
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :login, :null => false
t.string :crypted_password, :null => false
t.string :password_salt, :null => false
t.string :persistence_token, :null => false
t.timestamps
end
end
end
and did rake db:migrate
Included authlogic in the user model.
# /app/models/user.rb
class User < ActiveRecord::Base
acts_as_authentic
end
while trying to create a user in rails console User.create(name: "pria",password: "priya123", password_confirmation: "priya123")
iam getting
cant mass assign the protected attributes :name, :password, :password_confirmation
How can i rectify this error!
In your User model:
attr_accessible :name, :password, :password_confirmation
You must add these attributes to the attr_accessible list in your model.
For important information about mass-assignment and its security implications: http://guides.rubyonrails.org/security.html#mass-assignment
Related
I am trying to add user:references onto my already existing model. This is what I originally wrote:
rails g model Post title:string description:text
I do this to add the user:references by running rails generate migration add_user_to_posts user:references, I am receiving this error upon running rake db:migrate:
-- create_table(:users)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: table "users" already exists
I am reading the error and I understand I already have a User model, however, I want to add this attribute to the Post model, not the User model.
Db file:
Posts:
class CreatePosts < ActiveRecord::Migration[5.0]
def change
create_table :posts do |t|
t.string :title
t.text :description
t.timestamps
end
end
end
Trying to add the user to posts:
class AddUserToPosts < ActiveRecord::Migration[5.0]
def change
add_reference :posts, :user, foreign_key: true
end
end
Users:
class CreateUsers < ActiveRecord::Migration[5.0]
def change
create_table :users do |t|
t.string :name
t.string :uid
t.string :avatar_url
t.timestamps
end
add_index :users, :uid
end
end
However, rake db:migrate gives me the error above.
I need to implement activeuuid gem to have UUIDs instead of default Rails ids. we can implement it for creating new migration as:
class CreateStudents < ActiveRecord::Migration
def change
create_table :students, :id => false do |t|
t.uuid :id, :primary_key => true
t.string :name
t.string :email
t.timestamps
end
end
end
And in model we include ActiveUUID::UUID as:
class Student < ActiveRecord::Base
attr_accessible :email, :name
include ActiveUUID::UUID
end
Now I already have a database so how can I implement the activeuuid gem to have UUIDs instead of default Rails ids for existing DB?
Need to make changes in all migrations or what?
Need help in this regard. thanks
The UUID is stored as a binary field w/ 16 positions as I found here: https://github.com/jashmenn/activeuuid/blob/master/lib/activeuuid/patches.rb#L62
It worked for me (existing table without records):
def change
reversible do |dir|
change_table :payments do |t|
dir.up { t.change :id, :binary, limit: 16, :primary_key => true }
dir.down { t.change :id, :integer }
end
end
end
Don't forget to add those lines to your model as well:
include ActiveUUID::UUID
natural_key :at_least_one_field_here
More info in the github repo: https://github.com/jashmenn/activeuuid/
I am getting the following error after running my tests in the console:
ActiveRecord::StatementInvalid: SQLite3::SQLException: table users has no column named password: INSERT INTO "users"
user_test.rb:
class UserTest < ActiveSupport::TestCase
test "a user should enter a first name" do
user = User.new
assert !user.save
assert !user.errors[:first_name].empty?
end
test "a user should enter a last name" do
user = User.new
assert !user.save
assert !user.errors[:last_name].empty?
end
test "a user should enter a profile name" do
user = User.new
assert !user.save
assert !user.errors[:profile_name].empty?
end
test "a user should have a unique profile name" do
user = User.new
user.profile_name = users(:adam).profile_name
assert !user.save
assert !user.errors[:profile_name].empty?
end
end
users.rb:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :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,
:first_name, :last_name, :profile_name
validates :first_name, presence: true
validates :last_name, presence: true
validates :profile_name, presence: true,
uniqueness: true
has_many :statuses
def full_name
first_name + " " + last_name
end
end
users.yml:
dan:
first_name: "Dan"
last_name: "Can"
email: "dan#email.com"
profile_name: "dan"
password: "123456"
password_confirmation: "123456"
database.yml:
# SQLite version 3.x
# gem install sqlite3
#
# Ensure the SQLite 3 gem is defined in your Gemfile
# gem 'sqlite3'
development:
adapter: sqlite3
database: db/development.sqlite3
pool: 5
timeout: 5000
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
adapter: sqlite3
database: db/test.sqlite3
pool: 5
timeout: 5000
production:
adapter: sqlite3
database: db/production.sqlite3
pool: 5
timeout: 5000
What I believe to be my user migrate file:
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
t.string :first_name
t.string :last_name
t.string :profile_name
## Database authenticatable
t.string :email, :null => false, :default => ""
t.string :encrypted_password, :null => false, :default => ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, :default => 0
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, :default => 0 # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
## Token authenticatable
# t.string :authentication_token
t.timestamps
end
add_index :users, :email, :unique => true
add_index :users, :reset_password_token, :unique => true
end
end
I would like to know what is causing the error, but more importantly why.
When I removed the password and password_confirmation columns from the users fixture it passed the test with no errors. I'm told by a friend that is was likely due to an upgrade in devise.
It seems to me that the problem you have is, just as the error says, there is no password column in your User table. You have to add it to your migration:
t.string :password
Note, however, that I have never used Devise so I may be wrong about this.
I think there are a couple of possibilities here but I will focus on the immediate problem. If your Rake tasks are returning No command found, then it may be because Rake isn't installed on your computer. I would start there.
To install Rake, type in your terminal:
gem install rake
The reason why your code doesn't work is because your users table doesn't have a column named password. With rake db:migrate and rake db:test:prepare you are ensuring that any migrations you created are applied to your database.
Let me know the results.
I have this Rails 3.2 application running fine. I installed Rolify by following the steps below:
Add gem "rolify" to the Gemfile
Run bundle install
Run rails g rolify:role
Check the new migrations, the new files and the modified files (generated/modified by the command above).
Run rake db:migrate
At this point, I try to create/edit a User and I get the following error:
NoMethodError in UsersController#create
undefined method `user_id' for #<User:0x007f8f21f168e8>
Note that before I installed Rolify, everything was working fine, so the problem comes from Rolify.
Here are the migration, the new file and the modified file in question:
The new migration:
class RolifyCreateRoles < ActiveRecord::Migration
def change
create_table(:roles) do |t|
t.string :name
t.references :resource, :polymorphic => true
t.timestamps
end
create_table(:users_roles, :id => false) do |t|
t.references :user
t.references :role
end
add_index(:roles, :name)
add_index(:roles, [ :name, :resource_type, :resource_id ])
add_index(:users_roles, [ :user_id, :role_id ])
end
end
The new model:
class Role < ActiveRecord::Base
has_and_belongs_to_many :users, :join_table => :users_roles
belongs_to :resource, :polymorphic => true
end
The modified model:
class User < ActiveRecord::Base
rolify
has_secure_password
has_many :issues
acts_as_tenant(:client)
attr_accessible :email, :password, :password_confirmation, :username
validates :username, presence: true,
length: { within: 4..50 },
format: { with: /(?:[\w\d]){4,255}/ }
validates_uniqueness_to_tenant :username, case_sensitive: false
validates :email, presence: true,
uniqueness: { case_sensitive: false },
length: { within: 8..255 },
format: { with: /^[-a-z0-9_+\.]+\#([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i }
validates :password, presence: true, on: :create,
confirmation: true,
length: { within: 4..255 }
validates :password_confirmation, presence: true, on: :create
# NOTE: Used by SimpleForm to display the dropdown proerply
def to_label
"#{username}"
end
end
You can find the rest of the files in the project in the Github repo
Does anyone have a clue where the error comes from please?
This error is happening because the acts_as_tenant is (mistakenly) creating a validation for a user_id field on your User model. You can see this validator if you run this code inside rails c:
User._validators
I would recommend to switch to the apartment gem which appears to be more maintained than acts_as_tenant.
Am developing one website for which I have to do user login and registration form for the authentication purpose. My question is can we do this using only refinerycms and if it is possible please tell me how to do this. If it is not possible then please tell me which is the best approach. Am trying to implement user authentication using refinerycms. Am new to refinerycms.
Refinery uses devise so you can use that as well. You can create a model that might look something like this:
module Refinery
module Partners
class Partner < Refinery::Core::BaseModel
self.table_name = 'refinery_partners'
acts_as_indexed :fields => [:name]
validates :email, :presence => true, :uniqueness => true
#devise methods
devise :database_authenticatable, :recoverable, :rememberable, :trackable,:validatable, :authentication_keys => [:email]
end
end
end
and not to forget the migration:
class CreatePartnersPartners < ActiveRecord::Migration
def up
create_table :refinery_partners do |t|
t.string :email
t.string :name
## Database authenticatable
t.string :encrypted_password, :null => false, :default => ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, :default => 0
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
t.timestamps
end
end
def down
if defined?(::Refinery::UserPlugin)
::Refinery::UserPlugin.destroy_all({:name => "refinerycms-partners"})
end
if defined?(::Refinery::Page)
::Refinery::Page.delete_all({:link_url => "/partners/partners"})
end
drop_table :refinery_partners
end
end
This should create the basic model that you can use. To finish up, change the routes.rb in your extension to add devise routes:
devise_for :partners, :class_name => "Refinery::Partners::Partner",
:controllers => {:sessions => 'refinery/partners/sessions', :passwords => 'refinery/partners/passwords'}
and override refinery/partners/passwords_controller.rb
module Refinery
module Partners
class PasswordsController < Devise::PasswordsController
end
end
end
and refinery/partners/sessions_controller.rb
module Refinery
module Partners
class SessionsController < Devise::SessionsController
end
end
end
now you should have everything you need