Ruby on Rails:将另外一个模型的两个引用添加到另一个模型
问题描述:
我想知道在ruby on rails 4.0中实现我的情况的正确方法。Ruby on Rails:将另外一个模型的两个引用添加到另一个模型
可以说我有2个模特名为众议院和订购。
我的订单表应该有两列从和到这两个参考房子模型。
在这种情况下,这两个模型之间应该有什么关系? 注:我不需要从房子模型的任何参考订单模型。
我想有这样的事情在我的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
,因为我想利用房屋的领域在我的订单像
我想在命令模式这种类型的关系<%= form_for @order do |f| %>
... # order fields
<%= f.fields_for :house(from) do |i| %>
... # your house forms
<% end %>
<%= f.fields_for :house(to) do |i| %>
... # your house forms
<% end %>
...
<% end %>
是否有任何具体的方式来这在轨道?
P.S:我已经在这里看过这篇文章,但我认为这并不能完全解决我的问题。 Adding a Model Reference to existing Rails model
答
在创建订单迁移文件:
create_table :orders do |t|
..
t.integer :from_house_id
t.integer :to_house_id
..
end
在您的应用程序/模型/ 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 %>
享受!
答
添加这个答案,以防万一苏里亚的代码不能正常工作 - 我习惯了有指定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
。
+0
谢谢艾哈迈德,苏里亚的代码确实有效。 – Kranthi 2014-09-02 11:42:18
非常感谢。这正是我一直在寻找的。我认为它** **:from_house,:to_house,在订单模型中为accept_nested_attributes_for **。我已经做了这个改变。之后,我试图实现上述,但形式并没有出现。我的服务器不显示任何错误。所有领域的领域都没有显示。我不知道原因是什么? – Kranthi 2014-09-02 09:21:19
我的不好,有一个错字!抱歉。你需要在你的控制器中说'@ order.build_from_house'和'@ order.build_to_house',它会出现!如果答案有帮助,那么请接受答案,因为答案也可以帮助其他人。 :) – Surya 2014-09-02 09:24:29
它的工作。再次感谢。我已经接受了答案。 – Kranthi 2014-09-02 10:16:09