M
M
Mr Freeman2015-06-30 14:03:52
Ruby on Rails
Mr Freeman, 2015-06-30 14:03:52

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

I now want that when I call @conversion.count_conversions, undefined method `count_conversions' for nil:NilClass does not occur - and this occurs when @conversion is empty during aggregation. As
I understand it, I can get around this with
[email protected]? ? @conversion.count_conversions.to_i : 0,

but it's somehow too cumbersome for ruby ​​and I'm afraid that it's not "DRY" at all.
From Google, this is what I found, but still the error comes out
#Conversion model

  after_initialize :default_values

  def default_values
    self.count_conversions ||= 0
  end

# или вот такое вставляю, тоже нету смысла

  def count_conversions
    read_attribute(:count_conversions) or 0
  end

Explain to the beginner, please, what I'm confused about, what I can't understand, and how beautifully (and I'm almost sure that this can be done) to put the default values ​​into the model. Thank you!

Answer the question

In order to leave comments, you need to log in

4 answer(s)
T
thepry, 2015-06-30
@vladamir

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_conversionsnumber in
@count_conversions = @conversion.try(:count_conversions).to_i .

V
vsuhachev, 2015-06-30
@vsuhachev

@conversion.try(:count_conversions) || 0

E
Eugene Burmakin, 2015-06-30
@Freika

conversions is a model attribute? If yes, then such things are prescribed in the migration, like

t.string :conversions, default: 'some default value'

J
Jeiwan, 2015-06-30
@Jeiwan

[email protected]? ? @conversion.count_conversions.to_i : 0,
- in this case, it’s quite a solution, there’s nothing wrong with it. There is no repeat here.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question