Modeldagi model uyushmalarini qayta nomlash uchun yomon amaliyotmi?

class TransactionItem < ActiveRecord::Base
  belongs_to :transaction
end 

class Transaction < ActiveRecord::Base
  has_many :transaction_items

  def items
    self.transaction_items
  end
end



class CategoryItems < ActiveRecord::Base
  belongs_to :category
end 

class Category< ActiveRecord::Base
  has_many :category_items

  def items
    self.category_items
  end
end

In an effort to simplify the interface to Objects that have Items

bu erda ko'rganim yo'qmi? Ushbu maqsadga erishish uchun yoki undan yaxshi yo'l ?

category = Category.first
category.items
# instead of
# category.category_items

transaction = Transaction.first
transaction.items
# instead of
# transaction.transaction_items
1

2 javoblar

Boshqasi - bu klassni belgilash (qarang: has_many variantlari docs ):

has_many :items, :class_name => "CategoryItem"

Biroq yo'lingiz bilan hech qanday muammo yo'q.

Birgina ogohlantirish uyushmalar bilan yaqindan munosabatda bo'lgan (masalan, hujjat vositasi) qo'shimcha usul emas, balki "haqiqiy" nomni ishlatishi mumkin. Hech narsa emas, balki xabardor bo'lishi kerak bo'lgan narsa.

2
qo'shib qo'ydi

Yozganingizda:

has_many :category_items

Rails, CategoryItem modelini qidirishni avtomat tarzda biladi. Biroq siz assotsiatsiya nomini va unga ishora qilayotgan sinfni ajrim qilishingiz mumkin

has_many :items, :class_name => "CategoryItem" 
1
qo'shib qo'ydi