2

in domainpost.rb i have this:

class Domainpost < ActiveRecord::Base
  attr_accessible :content,  :additiona, :registerdate, :expiredate, :registerin, :price 

  belongs_to :user
  before_save { |domainpost| domainpost.content = content.downcase }

  before_validation :pricecheck

  validates :price, allow_blank: false, presence: true

  default_scope order: 'domainposts.created_at DESC'

  def pricecheck
    if  price.blank?
    price = 'no price'
  end
end

and it isnt work when price in post is blank after save is stil blank, any idea what i do wrong?

2
  • Maybe your price has numerical format, therefore string cannot be saved there? Commented Jul 2, 2013 at 9:10
  • @user2531122 is a local variable Commented Jul 2, 2013 at 9:11

2 Answers 2

4

It doesn't work because instead of setting attribute price of Domainpost instance, you set a local variable. Instead you should do:

def pricecheck
  self.price = 'no price' if price.blank?
end
Sign up to request clarification or add additional context in comments.

2 Comments

No need to explicitly put "self", as price = 'no price' and self.price = 'no price' is equal in this case. While inside pricecheck method, self points to the object being created/updated, so self is not needed.
You are wrong. When you use setter methods, it's necessary to explicitly point the receiver of message. Otherwise, only local variable will be set. Look at the example: price = 'no price' price # => 'no price' self.price # => nil.
1

As answer by @Merek Lipka and @muttonlamb you can try those approach but I suggest is defined a default value on your database side

like on your migration for price field simply do this

t.[price_data_type],:price,:default => "Your Default value"

Well this will take care of your check in model I believe

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.