Ruby on rails:将单个模型的2个引用添加到另一个模型
我想知道在rails 4.0的ruby中实现我的情况的正确方法。
可以说我有两个名为House and Order的模型。
我的订单表应该有两列引用房屋模型。
在这种情况下,我这两个模型之间的关系应该是什么? 注意:我不需要从房屋模型引用订单模型。
我希望在我的Order表中有这样的东西
t.references :house, as:from (this should create a column named from and should be of type integer, index of house table t.references :house, as:to (this should create a column named to and should be of type integer, index of house table
我想在订单模型中使用这种类型的关系,因为我想在我的订单中采用类似的房屋
... # order fields ... # your house forms ... # your house forms ...
在rails中有没有具体的方法?
PS:我已经在这里阅读了这篇文章,但我认为它并没有完全解决我的问题。 向现有Rails模型添加模型引用
在创建订单迁移文件中:
create_table :orders do |t| .. t.integer :from_house_id t.integer :to_house_id .. end
在你的app / models / order.rb中:
belongs_to :from_house, class_name: 'House' belongs_to :to_house, class_name: 'House' accepts_nested_attributes_for :from_house, :to_house
在您的观点中:
<%= form_for @order do |f| %> ... # order fields <%= f.fields_for :from_house do |i| %> ... # your from house forms <% end %> <%= f.fields_for :to_house do |i| %> ... # your to house forms <% end %> ... <% end %>
请享用!
添加此答案以防万一Surya的代码不起作用 – 我习惯于必须指定foreign_key:
class Order < ActiveRecord::Base belongs_to :from_house, :class_name => "House", :foreign_key => "from_id" belongs_to :to_house, :class_name => "House", :foreign_key => "to_id" end
只需确保Order
上有两个属性 – 一个是from_id
,另一个是to_id
。 从现在开始,您可以拨打order.from_house
和order.to_house
。