jeudi 2 juillet 2015

Ruby on Rails update ActiveRecord::Error string in the errors hash

I have an error message that says, Patient Contact Information: Value must be a 10 digit number

...but I want it to say Patient phone number must be a 10 digit number

I have an ActiveRecord Error being added here based on an attribute ...

<<-EOS

          # Validate as Phone Number
          unless self.#{ddv.attribute_name}.blank?
            self.update_attributes(#{ddv.attribute_name}: self.#{ddv.attribute_name}.gsub(/\\\D/, ''))
            if self.#{ddv.attribute_name}.length != 10
              errors.add(:#{ddv.attribute_name}, "must be a 10 digit number")
            end
          end
        EOS

while debugging I know that ddv.attribute_name = 'value' and ddv.model_name = "PatientContactInformation

I'm not sure how rails handles the next part, but ActiveRecord somehow adds the error message Patient Contact Information: Value must be a 10 digit number via the line errors.add(:#{ddv.attribute_name}, "must be a 10 digit

in other words, ddv.attribute_name is actually displaying ddv.model_name

the error message gets flashed on the screen in this action controller ...

  def submit_ucf
    @universal_claim_form = UniversalClaimForm.find(params[:id])
    @universal_claim_form.attributes = params[:universal_claim_form]
    begin
      @universal_claim_form.submitted_by = current_user.email
      if @universal_claim_form.save_then_submit(current_user.account_id)
        flash[:success] = 'Form was successfully submitted.'
        redirect_to universal_claim_forms_path(submitted: 'true')
      else
        #debugger
        #@universal_claim_form.errors.full_messages.join.gsub('Patient Contact Information: Value', 'Patient phone number')
        flash.now[:error] = "Form has errors and was unable to be submitted.<br/> " <<
            "<ul><li>#{@universal_claim_form.errors.full_messages.join("</li><li>")}</li></ul>".gsub('\n','<br/>')
        render 'edit'
      end
    rescue UniversalClaimFormPrescriptionDuplicateException => e
      flash[:error] = "Unable to complete.<br />\nThis submission was determined to be a duplicated based on the following:<br />\n#{e.message}"
      render 'edit'
    rescue => e
      logger.error "[UNIVERSAL_CLAIMS_FORM]#{e.message} : #{e.backtrace}"
      flash[:error] = 'There was an error while submitting the form.'
      render 'edit'
    end


  end

I tried adding the line @universal_claim_form.errors.full_messages.join.gsub('Patient Contact Information: Value', 'Patient phone number') (commented out above) to get the error message, convert to a string, and then replace the incorrect part with the correct message, but this doesn't work.

Any ideas?

Why minitest case are failing?

MyModel class:

class Post < ActiveRecord::Base
 validates_presence_of :value
 ...
end

my post.yml

one:
  row: 2
  col: 3
  name: 'Test'

MyTest cases

require 'test_helper'
class SimulationsModelTest < ActiveSupport::TestCase

def setup
 @post = Post.new
end

test 'post must have name' do
 @post.name = ' '
 assert @post.valid?
end

end

Why this above test cases are failing? However following test cases are passing

test 'post must have name' do
@post.name = ' '
assert_not @post.valid?

end

In my model I don't have presence => true set for name, Then why first test case are failing?

Rails 3 Kaminari fallback to first page if current page is out_of_range

I want to fallback to page 1 if the page number provided is out_of_range?.

For example if there are total 10 records and per_page is 5 which makes two pages. I want to fall back to page 1 if someone tries to hit page 3 which doesn't exist.

We are using kaminari (0.16.1).

How minitest testing framework works in rails?

I just started to learn testing with minitest but it sounds very confusing to me. What does this statement means?

test 'should not save simulations without name' do
 post = Post.new
 assert !post.save, 'Saved the simulations without a name'
end

Post Model

class Post < ActiveRecord::Base
  validates_presence_of :name , :type
  belongs_to :user
  before_create :check_validation
  validates :type,  :inclusion => { :in => 1..10, :message => 'The row must be between 1 and 10' }

 private
 def check_validation(data, type)
  ....
 end

What would be the minitest method for following conditions:

  • check if name, type parameter exist when creating a new object of Post class. How can I do it post_test class?
  • Is this test method are checking the presence of name in post?
  • How can I test check_Validation through PostTest class?
  • How to check throw error if posts is not belong to users?

I have already created post.yml file and user.yml file. How to proceed again. I tried to read ruby official documentation but it is not very helpful.

Thanks in adnvance

How to disable logs for fragment caching in rails

Hello I have a application in which continuously the log is being written by:

Read fragment views/locations/946-20150420170206 (0.1ms)
Read fragment views/locations/947-20150420170206 (0.1ms)
Read fragment views/locations/948-20150420170206 (0.1ms)
Read fragment views/locations/949-20150420170206 (0.1ms)
Read fragment views/locations/950-20150420170206 (0.1ms)
Read fragment views/locations/951-20150420170206 (0.1ms)
Read fragment views/locations/952-20150420170206 (0.1ms)
Read fragment views/locations/953-20150420170206 (0.1ms)
Read fragment views/locations/954-20150420170206 (0.1ms)
Read fragment views/locations/955-20150420170206 (0.1ms)
Read fragment views/locations/956-20150420170206 (0.1ms)
Read fragment views/locations/957-20150420170206 (0.1ms)
Read fragment views/locations/958-20150420170206 (0.1ms)
Read fragment views/locations/959-20150420170206 (0.1ms)
Read fragment views/locations/960-20150420170206 (0.1ms)
Read fragment views/locations/961-20150420170206 (0.1ms)
Read fragment views/locations/962-20150420170206 (0.1ms)
Read fragment views/locations/963-20150420170207 (0.1ms)
Read fragment views/locations/964-20150420170207 (0.1ms)
Read fragment views/locations/965-20150420170207 (0.1ms)
Read fragment views/locations/966-20150420170207 (0.1ms)
Read fragment views/locations/967-20150420170207 (0.1ms)
Read fragment views/locations/968-20150420170207 (0.1ms)
Read fragment views/locations/969-20150420170207 (0.1ms)
Read fragment views/locations/970-20150420170207 (0.1ms)
Read fragment views/locations/971-20150420170207 (0.1ms)
Read fragment views/locations/972-20150420170207 (0.1ms)

which is filling the log and making the file in some GB size. So I want to disable the logs for the cache read and write so I can stop this. I have tried various things:

module ActionView
  class LogSubscriber < ActiveSupport::LogSubscriber
    def logger
      @memoized_logger ||= Logger.new('/dev/null')
    end
  end
end

I kept this file in initializers folder but didn't help. The second thing in initializer I tried is:

Rails.cache.silence!

But still nothing changed. Also I tried this in production.rb:

config.cache_store.silence!

But this threw an error. I think probably there is no cache_store defined.

Also in the initializers I tried this:

# Create logger that ignores messages containing “CACHE”
class CacheFreeLogger < ::Logger
  def debug(message, *args, &block)
    super unless message.include? 'CACHE'
  end
end

# Overwrite ActiveRecord’s logger
ActiveRecord::Base.logger = ActiveSupport::TaggedLogging.new(
  CacheFreeLogger.new(STDOUT)) unless Rails.env.test?

Still no help.

I got another answer which might help but I don't know how to use this. Here is the link:

How to disable logging for rails 4 caching

Can someone please help me disabling the logs for this. Thanks in advance.

migrating from rails 2.3 to rails 3.1 ActiveRecord::UnknownAttributeError: unknown attribute

I am working on migrating an application from rails 2.3 to rails 3.1, most of the things are working but i am getting this error which i am not sure about. The error is

ActiveRecord::UnknownAttributeError: unknown attribute: package_id

Any help on this will be appreciated, Thanks.

how to solve Missing `secret_token` and `secret_key_base` for 'production' environment, set these values in `config/secrets.yml`

I generate secret key from the rake secret command and paste it in to the secrets.yml file under the production: secret_key_base:<%= ENV["SECRET_KEY_BASE"] %> instead of secret key. But still i can not hit to server via REST client. It showing following error after few minutes

We're sorry, but something went wrong.

If you are the application owner check the logs for more information.

Any one know the how to solve this problem????