Activerecord adds additional conditions in query - ruby-on-rails-3

For example I am doing something like this:
PlatformInformer.where(1)
and result query via
PlatformInformer.where(1).to_sql
is
SELECT `platform_informers`.* FROM `platform_informers` WHERE `platform_informers`.`platform` = 'android' AND `platform_informers`.`email` = 'voldemar#klops.ru' AND (1)
I didn't ask to add email and platform fields in where clause!
This problem causes when I am executing code inside PlatforInformer model methods. Default scope is doesn't set. What is the root of evil?
Rails 3.2.13
UPDATE:
class PlatformInformer < ActiveRecord::Base
include HasUniqueGenerator
attr_accessible :email, :platform,:secret_code,:activated,:invitation_sent
before_create :init_secret_code
PLATFORMS = %w(windows macos android ios)
def self.PLATFORMS
PLATFORMS
end
validates :platform, :presence => true,:inclusion => { :in =>PLATFORMS }
validates :email, :presence => true, :email => true
validates_uniqueness_of :email, scope: :platform
scope :confirmed, Proc.new { where(:activated => true) }
def several_platforms?
PlatformInformer.confirmed.find_all_by_email(self.email).count > 0
end
def send_confirmation
if already_subscribed?
activate!
else
PlatformInformerMailer.inform_me(self.id).deliver
end
end
def activate!
PlatformInformer.where(:email=>self.email).update_all(:activated=>true)
end
private
def init_secret_code
gen_unique_code :secret_code, 16
end
def already_subscribed?
PlatformInformer.confirmed.where(email: self.email).any?
end
end

Problem was in using first_or_create method, that created virtual scope with email and platform attributes.

Related

Options for validates_with

I'm not able to access the values, passed as option in 'validates_with'
My model:
class Person < ActiveRecord::Base
include ActiveModel::Validations
attr_accessible :name, :uid
validates :name, :presence => "true"
validates :uid, :presence => "true"
validates_with IdValidator, :attr => :uid
My Custom Validator:
Class IdValidator < ActiveModel::Validator
def validate(record)
puts options[:attr]
...
...
end
end
For testing purpose, I'm printing "options[:attr]" and all I see is ":uid" in the terminal and not the value in it. Please help!
When you pass in :attr => :uid, you're just passing in a symbol. There's no magic happening hereā€”it just takes the hash of options you've attached and delivers it as the options hash. So when you write it, you see the symbol you've passed.
What you probably want is
Class IdValidator < ActiveModel::Validator
def validate(record)
puts record.uid
...
...
end
end
Because validates_with is a class method, you can't get the values of an individual record in the options hash. If you are interested in a more DRY version, you could try something like:
class IdValidator < ActiveModel::Validator
def validate(record)
puts record[options[:field]]
end
end
class Person < ActiveRecord::Base
include ActiveModel::Validations
attr_accessible :name, :uid
validates :name, :presence => "true"
validates :uid, :presence => "true"
validates_with IdValidator, :field => :uid
end
Where you pass in the name of the field you want evaluated.

How to do conditional statement of validation from controller name in model

Example:
account_controller: do not validate a password
password_controller: validate a password
my idea is...
class User
include Mongoid::Document
...
validates :username,
:presence => true
validates :password,
:presence => { :if => :passord? }
...
def password?
# self.controller.to_s == 'password'
end
end
First of all, my idea is wrong?
Anyone have another good idea?
You can add virtual attribute to your model and conditional validation:
class User
attr_accessor :skip_password_validation
validates :password, :unless => :skip_password_validation
end
And put something like this into controller:
user.skip_password_validation = true

Why is user.save true but email shows as nil?

I'm using a nested model form for sign-up and am working through the kinks as a beginner. One issue that popped up in particular though that I don't really get is user.email is returning as nil.
Before I started playing around with the nested model form, I could create records in the console wihtout a problem. Now, however I can't create records and some of the latest records created have nil as their email. (I'm not sure if it has anything to do with the nested model at all, but that's my reference point for when it started going haywire.)
If I go into rails console to create a new User/Profile, I follow this process:
user = User.new
user.email = ""
user.password = ""
user.profile = Profile.new
user.profile.first_name = ""
...
user.profile.save
user.save
Everything goes well until user.save, which gives me the NameError: undefined local variable or method 'params' for #<User:>. In rails console it pinpoints to user.rb:25 in create_profile
So here is my User model:
class User < ActiveRecord::Base
attr_accessor :password, :email
has_one :profile, :dependent => :destroy
accepts_nested_attributes_for :profile
validates :email, :uniqueness => true,
:length => { :within => 5..50 },
:format => { :with => /^[^#][\w.-]+#[\w.-]+[.][a-z]{2,4}$/i }
validates :password, :confirmation => true,
:length => { :within 4..20 },
:presence => true,
:if => :password_required?
before_save :encrypt_new_password
after_save :create_profile
def self.authenticate(email, password)
user = find_by_email(email)
return user if user && user.authenticated?(password)
end
def authenticated?(password)
self.hashed_password == encrypt(password
end
protected
def encrypt_new_password
return if password.blank?
self.hashed_password = encrypt(password)
end
def password_required?
hashed_password.blank? || password.present?
end
def encrypt(string)
Digest::SHA1.hexdigest(string)
end
end
Can anyone help me figure out what's going on?
UPDATE: I tried changing my regex but I'm still seeing nil for email. Though a prior SO post said not to blindly copy regex without testing, so maybe I just didn't test it correctly. Good news though: I no longer get the error.
attr_accessor simply defines a "property" on the object and has no relation to the attributes of a ActiveRecord model (attributes is a Hash of the fields and values obtained from a table).
ActiveRecord does not save such "properties" as defined by the attr_accessor. (Essentially, attr_accessor defines a attr_reader and attr_writer (i.e. "getter" and "setter") at the same time)

Rails: awesome_nested_set issues

I am using the awesome_nested_set to do a simple drag and drop reordering of news items and the post happens but the position field in my DB is not updated...
Here is my model:
class NewsItem < ActiveRecord::Base
translates :title, :body, :external_url
attr_accessor :locale, :position # to hold temporarily
alias_attribute :content, :body
validates :title, :content, :publish_date, :presence => true
has_friendly_id :title, :use_slug => true
acts_as_indexed :fields => [:title, :body]
acts_as_nested_set
default_scope :order => "publish_date DESC"
# If you're using a named scope that includes a changing variable you need to wrap it in a lambda
# This avoids the query being cached thus becoming unaffected by changes (i.e. Time.now is constant)
scope :not_expired, lambda {
news_items = Arel::Table.new(NewsItem.table_name)
where(news_items[:expiration_date].eq(nil).or(news_items[:expiration_date].gt(Time.now)))
}
scope :published, lambda {
not_expired.where("publish_date < ?", Time.now)
}
scope :latest, lambda { |*l_params|
published.limit( l_params.first || 10)
}
# rejects any page that has not been translated to the current locale.
scope :translated, lambda {
pages = Arel::Table.new(NewsItem.table_name)
translations = Arel::Table.new(NewsItem.translations_table_name)
includes(:translations).where(
translations[:locale].eq(Globalize.locale)).where(pages[:id].eq(translations[:news_item_id]))
}
def not_published? # has the published date not yet arrived?
publish_date > Time.now
end
# for will_paginate
def self.per_page
20
end
end
Anyone know why this wouldn't work?

New validator class introduced in lib directory is not recognised and throws error

Unknown validator: 'email_format'
Rails.root: /home/saran/work_space/rails_apps/test_app
Application Trace | Framework Trace | Full Trace
app/models/user.rb:2
app/controllers/user_controller.rb:5:in `create'
my user model file as below:-
class User < ActiveRecord::Base
validates :email, :presence => true, :uniqueness => true, :email_format => true
end
my lib class introduced as below:
:~/work_space/rails_apps/test_app/lib$ cat email_format_validator.rb
class EmailFormatValidator < ActiveModel::EachValidator
def validate_each(object, attribute, value)
unless value =~ /^([^#\s]+)#((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
object.errors[attribute] << (options[:message] || "is not formatted properly")
end
end
end
I'm using Rails version 3.0
I had the same problem.
To solve it, I created a new folder "validators" in "config/lib".
Then I added this to config/application.rb:
config.autoload_paths += %W(#{config.root}/lib/validators/)
Modify the User Model like below:
class User < ActiveRecord::Base
require "email_format_validator"
validates :email, :presence => true, :uniqueness => true, :email_format => true
end