我有一个名为Purchase的模型和一个名为TicketType的模型。购买可以有许多票类型,票类可以有很多购买。
所以我有
class Purchase < ActiveRecord::Base
has_many :purchases_ticket_types, :class_name => 'PurchaseTicketType'
has_many :ticket_types, :through => :purchases_ticket_types
end
class TicketType < ActiveRecord::Base
has_many :purchases_ticket_types, :class_name => 'PurchaseTicketType'
has_many :purchases, :through => :purchases_ticket_types
end
class PurchaseTicketType < ActiveRecord::Base
set_table_name "purchases_ticket_types"
belongs_to :purchase
belongs_to :ticket_type
end
我知道,一旦ActiveRecord无法从驼峰类名中识别出正确的表名,表名的purchases_ticket_types就会出现问题。我结束了不得不调用set_table_name。
但最糟糕的是必须这样做:
purchase = Purchase.find(1)
purchase.purchases_ticket_types.each do |purchase_ticket_type|
puts 'join contains quantity: ' + purchase_ticket_type.quantity
puts 'ticket type name is: ' + purchase_ticket_type.ticket_type.name
end
看看那些冗长和重复的内容。一切正常,但看起来很难看。是否有更好的方法来命名多对多关联以避免此类事情: purchase.purchases_ticket_types.first.ticket_type.name ?
谢谢!
答案 0 :(得分:3)
如果您的应用程序除票证之外不出售任何其他内容,请使用TicketSale
作为联接模型名称(或简称为Sale
):
class Purchase < ActiveRecord::Base
has_many :ticket_sales
has_many :ticket_types, :through => :ticket_sales
end
class TicketType < ActiveRecord::Base
has_many :ticket_sales
has_many :purchases, :through => :ticket_sales
end
class TicketSale < ActiveRecord::Base
belongs_to :purchase
belongs_to :ticket_type
end