2014-09-01 65 views
0

我想知道在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

回答

1

在創建訂單遷移文件:

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 %> 

享受!

+0

非常感謝。這正是我一直在尋找的。我認爲它** **:from_house,:to_house,在訂單模型中爲accept_nested_attributes_for **。我已經做了這個改變。之後,我試圖實現上述,但形式並沒有出現。我的服務器不顯示任何錯誤。所有領域的領域都沒有顯示。我不知道原因是什麼? – Kranthi 2014-09-02 09:21:19

+0

我的不好,有一個錯字!抱歉。你需要在你的控制器中說'@ order.build_from_house'和'@ order.build_to_house',它會出現!如果答案有幫助,那麼請接受答案,因爲答案也可以幫助其他人。 :) – Surya 2014-09-02 09:24:29

+0

它的工作。再次感謝。我已經接受了答案。 – Kranthi 2014-09-02 10:16:09

0

添加這個答案,以防萬一蘇里亞的代碼不能正常工作 - 我習慣了有指定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_houseorder.to_house

+0

謝謝艾哈邁德,蘇里亞的代碼確實有效。 – Kranthi 2014-09-02 11:42:18

相關問題