Its not accepting Texts except Numeric figures. I created a Private method in my page.rb of my Model which is not callable from outside Model: page.rb so as to automatically fix in Permalink for users incase it's not provided. Despite, still not texts except numbers.
Here is few details about my code from my Model:
page.rb
class Page < ActiveRecord::Base
belongs_to :subject
has_many :sections
has_and_belongs_to_many :editors, :class_name => 'AdminUser'
acts_as_list :scope => :subject
before_validation :add_default_permalink
after_save :touch_subject
validates_presence_of :name
validates_length_of :name, :maximum => 255
validates_presence_of :permalink
validates_length_of :permalink, :within => 3..255
# use presence_of with length_of to disallow spaces
validates_uniqueness_of :permalink
# for unique values by subject use ":scope => :subject_id"
scope :visible, lambda {where(:visible => true)}
scope :invisible, lambda {where(:visible => false)}
scope :sorted, lambda {order('pages.position ASC')}
scope :newest_first, lambda {order('pages.created_at DESC')}
scope :search, lambda {|query| where('name LIKE ?', "%#{query}%")}
private
def add_default_permalink
if permalink.blank?
self.permalink = "#{id}-#{name.parameterize}"
end
end
def touch_subject
# touch is similar to:
# subject.update_attributes(updated_at, Time.now)
subject.touch
end
end
See picture for the error here
Error
if I add number up to 3 to this or put in just numbers, the program works well bet takes no text alone.
Related
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.
Below is error and the spec listed for my failing test , not sure why it keep getting failed with following message even though I see the method getting invoked on #user.save
Failure/Error: expect(#performer).should_receive(:store_performer)
(#<RSpec::Expectations::ExpectationTarget:0x007f9ec42b5808>).store_performer(any args)
expected: 1 time
received: 0 times
Once again
if I comment the should_receive I do see the method getting invoked (confirmed by virtue of puts) on #user.save call (During that I also examine the object_id of #performer inside the spec and inside the invoked method and found them to be same)
Note: Basically the store_performer , update_minimum_payout and update_to_be_paid are after_save callback
FYI the test case
it 'should invoke callback method' do
new_single_performer
#performer = #user.performer
expect(#performer).should_receive(:store_performer)
expect(#performer).should_receive(:update_minimum_payout)
expect(#performer).should_receive(:update_to_be_paid)
#user.save
end
User.rb
class User < ActiveRecord::Base
# Activity Log (formerly called User Activity)
cattr_accessor :current_user
has_one :performer,
:dependent => :destroy, :validate => true,:inverse_of => :user,:include => :profile # auto load the profile
## Some more association
scope :performers, where(:is_performer => true)
scope :active, where(:active => true)
## Some more scope
## Validation
validates_presence_of :first_name, :last_name, :email #, :password, :password_confirmation
validates_presence_of :site_id, :unless => :is_referrer?
validates_format_of :first_name, :message => "Characters not allowed: $\##!^&*(){}", :with => /^[\w\s]+z/
validates_format_of :last_name, :message => "Characters not allowed: $\##!^&*(){}", :with => /^[\w\s]+z/
validates_format_of :email, :message => "Invalid Email address", :with => /[\w\.\-\#]+z/
before_save :geocode, :if => :should_change_geocode?
before_save :check_role
after_create :update_vendor_id
after_create :notify_admin
after_save :store_changes,:if => :if_changed?
after_save :setup_account,:if => :studio_active_changed?
after_save :approval_notification,:if => :send_notification_present?
end
Performer.rb
class Performer < ActiveRecord::Base
belongs_to :user, :conditions => {:is_performer => true},:inverse_of => :performer
# validations
validates :date_of_birth, :address_1, :city, :state, :zipcode, :country, :phone_number,
after_save :store_performer
after_destroy :destroy_performer_source
after_save :update_minimum_payout ,:if => :minimum_payout_changed?
after_save :update_to_be_paid ,:if => :include_in_payouts_changed?
private
def store_performer
## Performer Source is Mongo document
performer_source = PerformerSource.find_or_create_by(:performer_id => self.id)
performer_source.update_attributes(performer_hash)
performer_source
end
def update_minimum_payout
self.current_payout.update_attributes(:minimum_payout => self.minimum_payout)
end
def update_to_be_paid
self.current_payout.update_attributes(:to_be_paid => self.include_in_payouts)
end
end
PerformerSource
class PerformerSource
include Mongoid::Document
end
JFI my Rspec Version is 2.12.2
There's Person class and PersonName class in AR, with has_many relationship. Now I want to validate the format of the PersonName model to be either alphabetic or space. Here is the code:
class Person < ActiveRecord::Base
has_many :names, :class_name => "PersonName", :dependent => :destroy
accepts_nested_attributes_for :names
end
class PersonName < ActiveRecord::Base
belongs_to :person
attr_accessible :full, :first, :middle, :last, :maiden, :title, :suffix, :nick
validates_format_of :full, :first, :middle, :last, :maiden, :title, :suffix, :nick, :with => /^[a-zA-Z\s]*$/, :on => :save
end
Seems the validates_format not get executed. When I run
PersonName.create(:full => '##$#').valid?
in the console, it returns true. I tried to change it to be :on => :create but it still return true. What could be the problem? Do I need to specify something in the Person class?
From rails documentation
Note: use \A and \Z to match the start and end of the string, ^ and $ match the start/end of a line
I think that is your problem
I found the reason, should use create! instead of create.
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!
I have rails 3 application with some models, like Product and User. I'm using "audited" gem to track changes for products, it's simple and nice working.
But I want to make special page where I want to put daily activity history. I need something like Audits.all.order("created_at") for first step, but there is no such model.
Question: How can I get all audits for today for all models?
I think you should query like Audited::Adapters::ActiveRecord::Audit.where("created_at >= ?", Date.today) according to the gem structure
To be able to access today's audits with:
#audits = Audit.today
Create an audit.rb file in app/models/ like:
Audit = Audited.audit_class
class Audit
scope :today, -> do
where("created_at >= ?", Time.zone.today.midnight).reorder(:created_at)
end
end
Audited also provides a few named scopes of its own that may prove useful:
scope :descending, ->{ reorder("version DESC") }
scope :creates, ->{ where({:action => 'create'}) }
scope :updates, ->{ where({:action => 'update'}) }
scope :destroys, ->{ where({:action => 'destroy'}) }
scope :up_until, ->(date_or_time){ where("created_at <= ?", date_or_time) }
scope :from_version, ->(version){ where(['version >= ?', version]) }
scope :to_version, ->(version){ where(['version <= ?', version]) }
scope :auditable_finder, ->(auditable_id, auditable_type){ where(auditable_id: auditable_id, auditable_type: auditable_type) }
my solution is simply to extend the audit object, e.g.
cat lib/audit_extensions.rb
# The audit class is part of audited plugin
# we reopen here to add search functionality
require 'audited'
module AuditExtentions
def self.included(base)
base.send :include, InstanceMethods
base.class_eval do
belongs_to :search_users, :class_name => 'User', :foreign_key => :user_id
scoped_search :on => :username, :complete_value => true
scoped_search :on => :audited_changes, :rename => 'changes'
scoped_search :on => :created_at, :complete_value => true, :rename => :time, :default_order => :desc
scoped_search :on => :action, :complete_value => { :create => 'create', :update => 'update', :delete => 'destroy' }
before_save :ensure_username
end
end
module InstanceMethods
private
def ensure_username
self.username ||= User.current.to_s rescue ""
end
end
end
Audit = Audited.audit_class
Audit.send(:include, AuditExtentions)