обновление базы данных после того, как действие create не работает - PullRequest
0 голосов
/ 23 января 2019

set_bonus(member_id, cookie) метод не работает.Я пытаюсь обновить ту же модель, которую возвращает self.set_signup_attribution(member_id, cookie, origin).

Переменная new_has_value возвращает {"currency"=>"usd", "type"=>"flat", "amount"=>1000}

Model.rb

# THIS METHOD WORKS
def self.set_signup_attribution(member_id, cookie, origin)
  return unless cookie.present?
  tracking_code = cookie
  attribution_channel = AttributionChannel.find_by tracking_code: tracking_code
  associated_member_record = Member.find member_id
  if attribution_channel.present?
    Attribution.create!({
      event: Attribution::SIGN_UP,
      attribution_channel: attribution_channel,
      associated: associated_member_record,
      extra: origin
    })
    set_bonus(member_id, cookie)
  else
    Rails.logger.info "Unknown Attribution Channel for tracking code: '#{ tracking_code }'"
  end
end


# THIS METHOD DOES NOT WORK. UPDATES THE DATABASE.
def self.set_bonus(member_id, cookie)
  epoch = Member.find_by(id: member_id).attribution_epoch
  attribution_code = AttributionChannel.find_by(tracking_code: cookie)
  duration_value = attribution_code.attribution_duration.downcase.split(' ')
  duration = duration_value.first.to_i.send(duration_value.last)
  return if cookie.present? && epoch.present?
  current_time = Time.now
  if attribution_code.bonus_config.present?
    if (current_time - epoch).to_i < duration
      hash_value = attribution_code.bonus_config
      new_hash_value = hash_value.assoc("sign_up")[1]
      value = Attribution.where(attribution_channel_id: attribution_code)
      if new_hash_value["type"] == "flat"
        value.update_all(
          bonus_amount: new_hash_value["amount"],
          bonus_currency: new_hash_value["currency"]
        )
      elsif new_hash_value["type"] == "percentage"
        value.update_all(
          bonus_amount: new_hash_value["amount"],
          bonus_currency: new_hash_value["currency"]
        )
      else
        {
          bonus_amount: "Doesn't exist",
          bonus_currency: "Doesn't exist"
        }
      end
    else
      "Do nothing"
    end
  else
    "Do nothing"
  end
  #cookie = nil
  binding.pry
end

Controller.rb

def index
  unless session[:just_signed_up]
    redirect_back_or_settings_page
  end
  Attribution.set_signup_attribution(current_user, cookies[:visit_attr], request.referer)
  Attribution.set_bonus(current_user, cookies[:visit_attr])
  session[:just_signed_up] = false
  @email = current_user.email
end

Как мне это сделать?Это то, что я пытался и не работает.Могу ли я объединить метод set_bonus с методом set_signup_attribution или чем-то еще?

Буду признателен за любую помощь.

Итак, углубимся в это:

Я слил set_bonus с set_signup_attribution и двумя полями (bonus_amount и bonus_currency), которые set_bonus метод должен обновитьвозвращает nil:

Attribution.create!(
  {
    event: Attribution::SIGN_UP,
    attribution_channel: attribution_channel,
    associated: associated_member_record,
    extra: origin
  }.merge(self.set_bonus(member_id, cookie).to_h)
)

С этим упражнением после использования binding.pry для этого set_bonus метода я понял, что он работает, но он возвращает nil, и я не знаю почему.Может ли это быть из-за того, что member_id отсутствует в модели или что-то в этом роде?

1 Ответ

0 голосов
/ 23 января 2019

в вашем выражении if вы должны вызвать метод set_bonus для соответствующего объекта.

    attribution = Attribution.create!({
      event: Attribution::SIGN_UP,
      attribution_channel: attribution_channel,
      associated: associated_member_record,
      extra: origin
    })
    attribution.set_bonus(member_id, cookie) if attribution.persisted?

Просто будьте осторожны, так как .create! выдаст ошибку в случае, если что-то не так, поэтому, возможно, будет лучше использовать

  attribution = Attribution.new(.....)
  if attribution.save
    attribution.set_bonus(.....)
  else
    Rails.logger.info  attribution.errors
  end

Надеюсь, это поможет.

Приветствия

...