Ruby on rails 4 Rails 4:多态性、单表继承、作用域。。。?
假设如下:Ruby on rails 4 Rails 4:多态性、单表继承、作用域。。。?,ruby-on-rails-4,Ruby On Rails 4,假设如下: class Customer < ActiveRecord::Base has_many :orders end class Order < ActiveRecord::Base belongs_to :customer end 但是如果我删除了用户id,那么我的关联就会中断。如何清理此问题?假设订单一次只能属于一个用户,我不建议您的表中有2个外键。使用单表继承可以获得相同的结果: class Customer < ActiveRecord::Base
class Customer < ActiveRecord::Base
has_many :orders
end
class Order < ActiveRecord::Base
belongs_to :customer
end
但是如果我删除了用户id,那么我的关联就会中断。如何清理此问题?假设订单一次只能属于一个用户,我不建议您的表中有2个外键。使用单表继承可以获得相同的结果:
class Customer < ActiveRecord::Base
has_many :orders
end
class RedCustomer < Customer
end
class BlueCustomer < Customer
end
class Order < ActiveRecord::Base
belongs_to :red_customer, foreign_key: 'customer_id'
belongs_to :blue_customer, foreign_key: 'customer_id'
end
它按预期工作:
order = Order.create
order.red_customer = BlueCustomer.create #=> raises <ActiveRecord::AssociationTypeMismatch>
order.red_customer = RedCustomer.create #=> Ok
order.blue_customer #=> nil
order.red_customer #=> #<RedCustomer id: ...>
order.blue_customer = BlueCustomer.create #=> Ok
order.red_customer #=> nil
order=order.create
order.red#u customer=BlueCustomer.create#=>加薪
order.red_customer=RedCustomer.create#=>确定
order.blue#u客户#=>零
order.red#u客户#=>#
order.blue_customer=BlueCustomer.create#=>确定
order.red#u客户#=>零
希望这对您有所帮助。谢谢您周到的回复。有些问题…Customer.type可以是“红色”、“蓝色”或“两者”。。。?此外,对于某些订单,客户是红色的,而对于其他订单,同一客户是蓝色的(请参见我的狗/帽子插图)。这意味着类型取决于顺序,这似乎有点让人困惑。哦,我明白了,我不明白它们可能两者兼而有之。是的,这有点让人困惑,哈哈。我会考虑一下并编辑我的回答谢谢你的帮助。脱机时有人建议使用“as:”(根据Rails的关联指南),但我仍然无法确定如何消除多余的用户id。我不确定“as:”别名在这种情况下会有什么帮助,但我很难想出解决这种情况的方法。在我看来,客户的类型只取决于订单?如果是这样,难道不应该有不同的顺序吗?比如红色的,蓝色的?只是猜测而已。如果一切都失败了,我会尝试在订单表中手动跟踪客户的类型,使用一列“customer\u type”手动设置为“Red”、“Blue”或“Both”。逻辑是这样的:some\u order.Red\u customer=best\u customer If best\u customer.have\u dog?;some\u order.blue\u customer=如果另一个客户戴着帽子,则另一个客户?。谢谢你看,我会继续找的。
class CreateCustomers < ActiveRecord::Migration
def change
create_table :customers do |t|
t.string :type
t.timestamps null: false
end
end
end
class CreateOrders < ActiveRecord::Migration
def change
create_table :orders do |t|
t.references :customer, polymorphic: true, index: true
t.timestamps null: false
end
end
end
order = Order.create
order.red_customer = BlueCustomer.create #=> raises <ActiveRecord::AssociationTypeMismatch>
order.red_customer = RedCustomer.create #=> Ok
order.blue_customer #=> nil
order.red_customer #=> #<RedCustomer id: ...>
order.blue_customer = BlueCustomer.create #=> Ok
order.red_customer #=> nil