0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

belongs_toの効力を舐めちゃいかん。

Posted at

ふとモデルをいじっていて「こいつなんでおるん?」という型に出会った。reward = product.rewards,,,のproductだ。もともとこいつがいる理由は知っていたのだが、忘れていた。そこで失礼ながら「なんでおるんや!」と投げかけてしまったのだ。


def donation_error
    reward = product.rewards.order(price: :desc).last
    errors.add(:base, "最低金額に達していません") if self.donation != nil && self.donation < reward.price
  end

class Patron < ApplicationRecord
  belongs_to :user
  belongs_to :product
  validates :donation, presence: true
  validate :donation_error
  belongs_to :reward
  has_many :notifications
  private

  def donation_error
    reward = product.rewards.order(price: :desc).last
    errors.add(:base, "最低金額に達していません") if self.donation != nil && self.donation < reward.price
  end
end

## 結論

belongs_toによってメソッドが与えられてる

Railsガイドさんによると

1 belongs_toで追加されるメソッド
belongs_to関連付けを宣言したクラスでは、以下の6つのメソッドを自動的に利用できるようになります。
association
association=(associate)
build_association(attributes = {})
create_association(attributes = {})
create_association!(attributes = {})
reload_association
Railsガイドさん

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?