Answer the question
In order to leave comments, you need to log in
How to specify default values in a model in rails?
Hi all. I'm studying rails, but I can't find an answer to this question anywhere, or I just can't figure out why it doesn't work.
Have a request
@conversion = Conversion.joins(:track)
.select('SUM(conversions.revenue) as sum_revenue, COUNT(*) as count_conversions')
.group('tracks.campaign_id')
.where(:tracks => { :campaign_id => campaign_id })
.order('tracks.campaign_id ASC')
.first
[email protected]? ? @conversion.count_conversions.to_i : 0,
#Conversion model
after_initialize :default_values
def default_values
self.count_conversions ||= 0
end
# или вот такое вставляю, тоже нету смысла
def count_conversions
read_attribute(:count_conversions) or 0
end
Answer the question
In order to leave comments, you need to log in
I found this on google, but still get the error.
Yes, because if your query didn't find anything, then first will return nil. And at objects of a class nil it is necessary for you of a method is not present.
The output could be the initialization of a new object:@conversion = Conversion.joins(:track) .select('SUM(conversions.revenue) as sum_revenue, COUNT(*) as count_conversions') .group('tracks.campaign_id') .where(:tracks => { :campaign_id => campaign_id }) .order('tracks.campaign_id ASC') .first @conversion ||= Conversion.new
Although, in my opinion, if you need to get the value of this method several times, then yes, use an additional variable for this.
UPDATE: Or so, if it is important that there is always a@count_conversions
number in@count_conversions = @conversion.try(:count_conversions).to_i .
conversions is a model attribute? If yes, then such things are prescribed in the migration, like
t.string :conversions, default: 'some default value'
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question