2011-05-03 82 views
2

我在用戶和目標之間有一對一的關係。我想要構建一個顯示用戶目標的表單。問題是我的代碼只在用戶已經定義了目標時才起作用。沒有目標時,不顯示文本字段。嵌套表單和一對一關係

<%= user_builder.fields_for :goal do |goal_builder| %> 
    <%= goal_builder.text_field :goal %> 
<% end %> 

Rails是否提供了一種簡單的方法來執行此操作?

+0

如果目標只有一個字段,爲什麼不把它存儲在用戶模型中? – ramblex 2011-05-03 15:33:16

回答

6

這是我會怎麼做:

class User < ActiveRecord::Base 
    has_one :goal 
    accepts_nested_attributes_for :goal 
    after_initialize do 
    self.goal ||= self.build_goal() 
    end 
end 
+0

其次是一對多的情況下:) – 2011-05-03 15:35:42

+0

thx的答覆。當我使用Goal.new時,當目標已經定義時,它總是會創建一個新的目標對象。我能以某種方式有條件地創造新的目標嗎? – Tarscher 2011-05-03 15:36:46

+0

哦。當然是! – 2011-05-03 15:43:05

1

你可以用accepts_nested_attributes_for做到這一點很容易。

在視圖中,如您有:

<%= user_builder.fields_for :goal do |goal_builder| %> 
    <%= goal_builder.text_field :goal %> 
<% end %> 

在用戶模式:

class User < ActiveRecord::Base 
    has_one :goal # or belongs_to, depending on how you set up your tables 
    accepts_nested_attributes_for :goal 
end 

參見nested attributes的文檔,以及form_for method以獲取更多信息。