The provided regular expression is using multiline anchors (^ or $)? [duplicate] - ruby

This question already has answers here:
Regular expressions with validations in RoR 4
(5 answers)
Closed 8 years ago.
I'm getting an error:
The provided regular expression is using multiline anchors (^ or $). Did you mean to use \A and \z, or forgot to add the :multiline => true option?
when loading only one page in my Rails application.
It highlights the model it's using saying the error is:
class Associate < Locations::Associate
This is the model:
class Associate < Locations::Associate
# Returns an array of permissions which are valid at the associate level.
#
def self.associate_permissions
ASSOCIATE_PERMISSIONS
end
# Generates an array of permission values that can be used in the new or edit
# template.
#
def permission_list
my_permissions = (permissions || '').split(/,/)
list = []
Associate.associate_permissions.each do |value|
list << {:label => value[0], :value => value[1], :checked => my_permissions.include? (value[1])}
end
list
end
end
The controller:
class AssociatesController < ApplicationController
def index
#associates = Associate.paginate :order => 'code',
:page => params[:page], :per_page => 50
respond_to do |format|
format.html # index.html.erb
format.json { render json: #associates }
end
end
end
Can anyone tell me how to solve this error?

I am assuming that you are getting the error while rendering an index view.
Update the index action with
#associates = Associate.order('code').paginate(:page => params[:page], :per_page => 50)
instead of
#associates = Associate.paginate :order => 'code',
:page => params[:page], :per_page => 50

I figured out my issue. I have a gem that runs most of my models. in the gems model I have:
class Locations::Associate < Locations::Database
require 'digest'
attr_accessible :code, :email, :include_on_reports, :name,
:permissions, :phone, :writer
has_many :associate_branches, :dependent => :destroy
validates :code, :presence => true, :uniqueness => true,
:format => { with: /^[A-Z]{3}\d{4}$/, on: :create }
.....
end
I had to change the regex to:
validates :code, :presence => true, :uniqueness => true,
:format => { with: /\A[A-Z]{3}\d{4}\z/, on: :create }
thanks for all the help.

Related

Active admin nested form not working Error: too many arguments for format string

Following is my code block of state Model, SatatImage Model and Active Admin Code. In active admin when I try to create a new record or Edit a --record that time I show an error on production server. but works on my localhost in development mode,
---------Error---------------------------
too many arguments for format string
app/admin/state.rb:49:in `block (2 levels) in '
I am using Ruby 1.9, Rails 3,2, activeadmin (0.6.0)
======State Model===============
class State < ActiveRecord::Base
attr_accessible :name, :code
validates :code, :uniqueness => true
has_one :state_image, :dependent => :destroy
accepts_nested_attributes_for :state_image, :allow_destroy => true
.......
end
==============StatImage Model=============
class StateImage < ActiveRecord::Base
attr_accessible :state_id, :stateimage, :image_name
belongs_to :state
mount_uploader :stateimage, StateUploader
end
=======Active Admin part=================
ActiveAdmin.register State do
.....
form(html:{multipart:true}) do |f|
f.inputs "State Form" do
f.input :name, required:true
f.input :code, required:true
end
#line-49#
f.inputs "StateImage", for:[:state_image, f.object.state_image || StateImage.new] do |p|
p.input :stateimage, :as => :file, :label => "Image"
end
f.buttons :submit
end
end
I am using
f.semantic_fields_for
And Formtastic requires you to wrap ALL inputs in an "inputs" block. So this should be:
f.inputs 'State Image' do
f.semantic_fields_for :state_image, (f.object.state_image || StateImage.new) do |p|
p.inputs do
p.input :stateimage, :as => :file, :label => "Image"
p.input :_destroy, :as => :boolean, :required => false, :label => 'Remove image'
end
end
end
Please try this:
form :html => { :enctype => "multipart/form-data" } do |f|
Also upgrade you activeadmin version to 0.6.6

ActiveAdmin calculations

I want to implement some calculation to my admin interface, so i have a product resource, at this resource you see a list of services that I do, such as airbrushing, price on application considered as, for example (1 $ per 1 square cm).
How i can better realize this idea?
I would like to see when a user pushing a button "New Product" it was a field where he writes the number of square centimeters and on the basis of these dimensions, it automatically render the required amount in the currency.
Rails 4.1.0
ActiveAdmin 1.0.0
ruby 2.1
Just now you can only type a fixed price, like fixed price for 1 product/service.
app/admin/product.rb
ActiveAdmin.register Product, { :sort_order => :name_asc } do
# Scopes
scope :all, :default => true
scope :available do |products|
products.where("available < ?", Date.today)
end
scope :drafts do |products|
products.where("available > ?", Date.today)
end
scope :featured_products do |products|
products.where(:featured => true)
end
# Permitted parameters
permit_params :article_id, :title, :description, :price, :featured, :available, :image_file_name
# Displayed columns
index do
selectable_column
column :article, :sortable => :article
column :title, :sortable => :title
column :description
# Currency helper
column :price, :sortable => :price do |cur|
number_to_currency cur.price, locale: :ru
end
column :featured
column :available
# column :image_file_name
actions
end
# Product details
show do
panel "Product Details" do
attributes_table_for product do
row("Article") { link_to product.article }
row("Title") { product.title }
row("Description") { product.description }
row("Price") { product.price }
row("Featured") { product.featured }
row("Available on") { product.available }
row("Image") { image_tag("products/" + product.image_file_name) }
end
end
end
# Filters
filter :article, :as => :select
filter :title, :as => :select # :check_boxes (for checkboxes)
filter :price, :as => :select
filter :available, :as => :select
filter :featured, :as => :check_boxes
end
app/models/product.rb
class Product < ActiveRecord::Base
# Relationship
belongs_to :article
# Named Scopes
scope :available, lambda{ where("available < ?", Date.today) }
scope :drafts, lambda{ where("available > ?", Date.today) }
# Validations
validates :article, :title, :description, :price, :available, :presence => true
validates :featured, :inclusion => { :in => [true, false] }
end
app/models/article.rb
class Article < ActiveRecord::Base
# Relationship
has_many :products, :dependent => :delete_all
# Validations
validates :title, :description, :presence => true
# Define for display a article for products as article code
def to_s
"#{title}"
end
end

Rails - has_many build method not saving association

I'm having some trouble trying to make association works.
My models looks like:
advertise.rb
class Advertise < ActiveRecord::Base
belongs_to :user
belongs_to :country
has_many :targets
# has_many :hss, :through => :targets
validates :description, :presence => true
validates :url, :presence => true
validates :country_id, :presence => true
validates :kind, :presence => true
attr_accessible :description, :hits, :url, :active, :country_id, :kind
KINDS = {
'1' => 'Commoditie',
'2' => 'Service',
}
HS = {
'1' => 'Section',
'2' => 'Chapter',
'4' => 'Heading',
'5' => 'SubHeading 1',
'6' => 'SubHeading 2',
}
end
hs.rb
class Hs < ActiveRecord::Base
attr_accessible :code, :kind
has_many :targets
has_many :advertises, :through => :targets
end
target.rb
class Target < ActiveRecord::Base
attr_accessible :advertise_id, :hs_id
belongs_to :advertise
belongs_to :hs
end
advertises_controller.rb
def new
#advertise = Advertise.new
#countries = Country.all
end
def create
#advertise = current_user.advertises.build(params[:advertise])
if #advertise.save
flash[:notice] = 'Advertise created with successful'
redirect_to root_path
else
render :new
end
end
the form for creating a new Ad.
/advertises/new.html.haml
%table.table.table-striped
%tr
%td{:colspan => 2}= advertise.input :url, :required => true
%tr
%td{:colspan => 2}= advertise.input :description, :required => true, :as => :text, :input_html => { :cols => 50, :rows => 3 }
%tr
%td{:colspan => 2}= advertise.input :country_id, :collection => #countries, :as => :select, :label => 'Origin', :required => true
%tr
%td{:colspan => 2}= advertise.input :kind, :collection => Advertise::KINDS.map(&:reverse), :as => :select, :label => 'Type', :required => true
%tr
%td{:colspan => 2}= advertise.input_field :active, as: :boolean, inline_label: 'Active'
=fields_for :targets do |target|
%tr
%td= select_tag :hs_kind, options_for_select(Advertise::HS.map(&:reverse).insert(0,'') )
%td= target.select :hs_id, ''
The hash params:
[3] pry(#<AdvertisesController>)> params
=> {"utf8"=>"✓",
"authenticity_token"=>"fOdn4NYLg/4HXruWURZPf9DYVT4EQzbaTRTKZvX1ugY=",
"advertise"=>
{"url"=>"http://test.com",
"description"=>"test",
"country_id"=>"17",
"kind"=>"2",
"active"=>"1"},
"hs_kind"=>"2",
"targets"=>{"hs_id"=>"487"},
"commit"=>"Create Advertise",
"action"=>"create",
"controller"=>"advertises"}
The hash seems ok to me, but it creates only the Advertise, and not creates the target for the advertise associated.
Any though? Maybe a wrong model association.
Thanks in advance.
try changing
=fields_for :targets do |target|
to
= advertise.fields_for :targets do |target|
and add the following to advertise.rb
accepts_nested_attributes_for :targets
attr_accessible :targets_attributes # just add targets_attributes to attr_accessible
be warned that when you do this, advertise objects that has no targets will not show the fields for targets. you have to build a new target object associated to advertise in order to show the fields
# example: on the new action of the controller
#advertise = Advertise.new
#advertise.targets.build

Is it possible to combine with_options and :if for conditional validations?

I'm trying to use with_options to group my conditional validations together for admin users.
The second validation for username uniqueness ends up overriding the with_options condition.
Is there a better way to do this? Or should I just forget about with_options and write two separate statements?
with_options :if => Proc.new { |user| user.admin? } do |admin|
admin.validates :email, :presence => true
admin.validates :username, :uniqueness => true, :if => Proc.new { |user| user.category == "customized_username" }
end
If you only have these two validations, I don't think it's a bad idea to drop the with_options block and just add the conditions directly to each validation:
admin.validates :email, :presence => true, :if => Proc.new { |user| user.admin? }
admin.validates :username, :uniqueness => true, :if => Proc.new { |user| user.admin? && user.category == "customized_username" }
Another thing you may want to consider is Single table inheritance (STI) instead of using a boolean field. I would recommend this if you find yourself doing user.admin? all over your application. Using STI, you would have regular users and Admin users and each could contain different logic for each class. The only real change you'd need to make is changing your "admin" field to "type" and making it a string:
class User < ActiveRecord::Base
end
class AdminUser < User
validates :email, :presence => true
validates :username, :uniqueness => true, :if => Proc.new { |user| user.category == "customized_username" }
end
You should use two lines, however, it is cleaner to have method than repeat the same logic in Proc.
validates :email, :presence => true, :if => :admin?
validates :username, :uniqueness => true, :if => [:admin?, :custom_user?]
def custom_user?
category == "customized_username"
end
Use unless instead:
with_options :unless => Proc.new { |user| !user.admin? } do |admin|
admin.validates :email, :presence => true
admin.validates :username, :uniqueness => true, :if => Proc.new { |user| user.category == "customized_username" }
end

Rails Active Record Validation condition base

class Material < ActiveRecord::Base
belongs_to :material_type
belongs_to :product_review
validates :url, :presence => true, :if => :url_presence?
validates :video, :presence => true, :if => :video_presence?
def url_presence?
if !self.title.blank? and self.material_type.title.eql? :url
true
end
end
def video_presence?
if !self.title.blank? and self.material_type.title.eql? :video
true
end
end
has_attached_file :video,
:url => "/system/video/:id/:attachment/:style/:basename.:extension",
:path => ":rails_root/public/system/video/:id/:attachment/:style/:basename.:extension",
:default_url => "/image/video.png"
end
I assumption if its finds Title fields fill and material_type is url than it perform validation for url field presence validation check, but it not helpful
I think you need to compare strings, not symbols.
validates :url, :presence => true, :if => :url_present?
validates :video, :presence => true, :if => :video_present?
def url_present?
self.title.present? and self.material_type.title == "url"
end
def video_present?
self.title.present? and self.material_type.title == "video"
end

Resources