开发者

Is it OK to manage associations manually?

开发者 https://www.devze.com 2022-12-26 07:43 出处:网络
Here are the relevant models: User Product Order A User can sell or buy products An order has a buyer, a seller and one product

Here are the relevant models:

User Product Order

A User can sell or buy products An order has a buyer, a seller and one product

I know that I can do this with a HABTM relationship between orders and user, but is seems to me like it would be simpler to put in the Order table the following columns:

:seller_id :buyer_id

and manage those relationships manually as orders are onl开发者_StackOverflowy created once and never edited. However, this doesn't seem very Rails-like and I am wondering if I am missing something conceptually at the HABTM relationship.


no it's not a ruby way although you are not edited order once it created.

Use following relationship in model i think it will work. No check though

User.rb
has_many :users
has_many :purchase, :class_name =>Order, :foreign_key=>'buyer_id'
has_many :sells, :class_name =>Order, :foreign_key=>'seller_id'

Product.rb
belongs_to :user
has_many :orders

Order.rb
belongs_to :buyer, :class_name =>User, :foreign_key=>'buyer_id'
belongs_to :seller, :class_name =>User, :foreign_key=>'seller_id'
belongs_to :product


You should use Rails associations for this. The has_many association is a better choice for your scenario.

class User < ActiveRecord::Base
  has_many :buys,  :class_name => "Order", :foreign_key => "buyer_id"
  has_many :sales, :class_name => "Order", :foreign_key => "seller_id"
end

class Product < ActiveRecord::Base
end

class Order < ActiveRecord::Base
  belongs_to :product
  belongs_to :buyer,  :class_name => "User", :foreign_key => "buyer_id"
  belongs_to :seller, :class_name => "User", :foreign_key => "seller_id"
end

Now you can use the association as follows:

current_user.buys.create(:seller => u, :product => p)
current_user.buys
current_user.sells
0

精彩评论

暂无评论...
验证码 换一张
取 消