Datamapper does not save/update entry - ruby

I'm currently developing a quick little sinatra app, and I've managed to conquer authentication quite easily. However I cannot for the life of me get password changing to work. I'm using the code below with Datamapper, and although it reaches the redirect, the password does not change.
user = User.first(:token => session[:user])
if params[:newpassword] == params[:newpasswordconfirm]
if BCrypt::Engine.hash_secret(params[:oldpassword], user.salt) == user.password_hash
user.password_hash = BCrypt::Engine.hash_secret(params[:newpassword], user.salt)
user.save
redirect '/'
I've also tried
user = User.first(:token => session[:user])
if params[:newpassword] == params[:newpasswordconfirm]
if BCrypt::Engine.hash_secret(params[:oldpassword], user.salt) == user.password_hash
user.update(:password_hash = BCrypt::Engine.hash_secret(params[:newpassword], user.salt)
redirect '/'
however this also fails to update the value. Unsure what I've done wrong.
class User
include DataMapper::Resource
attr_accessor :password, :password_confirmation
property :id, Serial
property :username, String, :required => true, :unique => true
property :password_hash, Text
property :salt, Text
property :token, String
validates_presence_of :password
validates_confirmation_of :password
validates_length_of :password, :min => 6
end

Related

DataMapper case-insensitive unique validation

I have something like:
class User
include DataMapper::Resource
property :id, Serial
property :username, String, :unique => true
end
post '/signup' do
user = User.create(username: params['username'])
if user.save
puts "New user was created"
else
puts user.errors
end
end
Parameter :unique => true is case-sensitive. It does not prevent to create users with usernames 'admin' and 'Admin'. How can I validate case-insensitive username unique, with out downcased username property, so users can make usernames as they choose.
You can provide your own custom validation:
class User
include DataMapper::Resource
property :id, Serial
property :username, String
validates_with_method :username,
:method => :case_insensitive_unique_username
def case_insensitive_unique_username
User.first(conditions: ["username ILIKE ?", self.username]).nil?
end
end
Note that ILIKE will only work with PostgreSQL, you will have to find out how to find records case insensitively with your specific adapter for yourself.

undefined method `password' for #<User:1123123123>

I'm following this video tutorial and learning how to create authentication from scratch:
http://www.youtube.com/watch?v=O5RDisWr_7Q
Here is my migration file for User:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :email
t.string :password_hash
t.string :password_salt
t.timestamps
end
end
end
And my controller:
class UsersController < ApplicationController
def new
#user = User.new
end
def create
#user = User.new(params[:users])
if #user.save
redirect_to root_url, :notice => "Signed up!"
else
render "new"
end
end
end
And finally my Model:
class User < ActiveRecord::Base
attr_accessible :email, :password_hash, :password_salt
before_save :encrypt_password
validates_confirmation_of :password
validates :password, presence: true
validates :email, presence: true
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
end
Now, I think I know why this error is firing; obviously the #user.save call is trying to save the value in password to the password field in the User table, but that field doesn't exist in the database. In the video he mentions that to fix this bug I should just add: attr_accessible :password to my model and it should work, but I get the following error:
NoMethodError in UsersController#create
undefined method `password' for #
app/controllers/users_controller.rb:8:in `create'
Any suggestions? I just would like to take advantage of the validations that come with using a strongly typed model instead of loose html fields.
You have attr_accessible :password_hash, :password_salt, but I think it should be attr_accessible :password together with attr_accessor :password since you need a virtual attribute password on which you work in your encrypt_password method. So:
class User < ActiveRecord::Base
attr_accessible :email, :password
attr_accessor :password
end
attr_accessor creates the virtual attribute which is not available as a database field (therefore virtual).
attr_accessible is a security mechanism to white-list attributes which are allowed to be set through mass-assignment like you do with User.new(params[:users])

"Retweets" with Datamapper

I want to impliment something which is similar to Twitter Repost System, therefore I will use this as an example. So let's say I have a Tweet Model and I want to allow other user to repost a certian tweet of another user, how do I impliment something like this?
I thought I would be a cool idea to put the retweet class into the tweet to be able to acess the repost too when I use Tweet.all to recive all tweets stored in the database, but somehow I didn't worked as expected...
The following Code is just an example which should show how to impliment this even if it is not working...
Any ideas how I could build a working repost model which also allows me to access both tweets and retweet by using Tweet.all?
class Tweet
class Retweet
include DataMapper::Resource
belongs_to :user, key => true
belongs_to :tweet, key => true
end
include DataMapper::Resource
property :text, String
property :timestamp, String
belongs_to :user
end
Important: I should be carrierwave compatible.
class Tweet
include DataMapper::Resource
property :id, Serial
has n, :retweets, 'Tweet', :child_key => :parent_id
belongs_to :parent, 'Tweet', :required => false
belongs_to :user
def is_retweet?
self.parent_id ? true : false
end
end
original = Tweet.create :user => user1
retweet = Tweet.create :parent => original, :user => user2
retweet.is_retweet? # => true

Paperclip dosnt save attachments if password has attr_accessor

My project:
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :email,
:password,
:password_confirmation,
:first_name,
:last_name,
:birth_date,
:residence,
:user_role,
:show_email,
:avatar
as_attached_file :avatar,
:default_url => '/images/system/user_avatars/default/default_avatar.png',
:url => "/public/images/system/user_avatars/:id_:style.:extension",
:path => "/public/system/user_avatars/:id_:style.:extension"
def update_profile(user_id, params) #params has :category and :user params
#user = User.find(user_id)
#user.update_attributes(params[:user])
return params[:category]
end
end
So, from my controller i call this method and i get no error. Paperclip shows attachment saved. The database is updated, but the image file is not saved. I have an registration made from scratch, so that's why i have the "attr_accessor :password"
I checked:
Have :multipart => true in form
Have attr_accessible :avatar in user model
Can any one give me some lead, cos i cant figure, why paperclip dosnt save the file.
Set attr_accessible :avatar_file_name as well, and you also need a paperclip.rb initializer:
require "paperclip"
Paperclip.options[:command_path] = "/ImageMagick"
And, of course, have ImageMagick installed.

Associating one class to belong to two different classes in DataMapper using Sinatra

I am working with DataMapper and Sinatra to create a simple app. Here's the structure:
The app has Accounts. Each account has users and campaigns. Each user has comments that should be related to a specific campaign.
Comments should ideally have a user_id and a campaign_id to relate them both.
How can I relate the 2 together? Here's the code that I have which does not work:
class Account
include DataMapper::Resource
property :id, Serial
property :mc_username, String, :required => true
property :mc_user_id, String, :required => true
property :mc_api_key, String, :required => true
property :created_at, DateTime
property :updated_at, DateTime
has n, :users
has n, :campaigns
end
class User
include DataMapper::Resource
property :id, Serial
property :name, String, :required => true
property :email, String, :required => true
property :is_organizer, Integer
property :created_at, DateTime
property :updated_at, DateTime
belongs_to :account, :key => true
has n, :comments
end
class Campaign
include DataMapper::Resource
belongs_to :mailchimpaccount, :key => true
has n, :comments
property :id, Serial
property :cid, String
property :name, String
property :current_revision, Integer
property :share_url, Text, :required => true
property :password, String
property :created_at, DateTime
property :updated_at, DateTime
end
class Comment
include DataMapper::Resource
belongs_to :campaign, :key => true
belongs_to :user, :key => true
property :id, Serial
property :at_revision, Integer
property :content, Text
property :created_at, DateTime
end
With this code, I can't save a comment since I can't figure out how to associate it to a campaign and a user at the same time. I can't really get my head around wether I should even try to relate them at all using DataMapper.
I would love to know if this code is correct, how I can go about creating a comment that is related to both. If not, what structure and associations would be optimal for this scenario?
Thanks so much for the help!
What you're doing seems reasonable, I think you just need to get rid of the :key => true options since you don't really want those associations to be part of the comment's primary key.
You should probably start by looking at these datamapper docs on properties.
Alex is right, what you have there is a composite primary key. This would be ok if you only wanted each user to have one comment per campaign, but this is probably not the case but you do want to make sure that the comment is associated to a user and a campaign so use required => true, like so:
class Comment
include DataMapper::Resource
property :id, Serial
belongs_to :campaign, :required => true
belongs_to :user, :required => true
property :at_revision, Integer
property :content, Text
property :created_at, DateTime
end
Also your key in the campaign model may be problematic:
class Campaign
include DataMapper::Resource
belongs_to :mailchimpaccount, :key => true
#......
You probably just want to make that required too.
So it seems that my thinking was correct. I can relate a comment to both a user and a campaign in this way:
# Get a user and a campaign first that we can relate to the comment
user = User.get(user_id)
campaign = Campaign.get(campaign_id)
comment = Comment.new
comment.content = "The comment's content"
user.comments << comment # This relates the comment to a specific user
campaign.comments << comment # This now relates the comment to a specific campaign
comment.save # Save the comment
Dangermouse's suggestion to replace the :key => true option with :required => true also helped clean up the schema. Thanks!

Resources