2013-03-12 44 views
0

我被卡住了。 我有以下模型:配置文件,用戶,工作。Rails fields_for沒有出現

用戶有一個配置文件,配置文件有很多工作。

class Profile < ActiveRecord::Base 

    belongs_to :user 
    has_many :jobs 

    attr_accessible :user_id, :first_name, :last_name, :headline,:jobs_attributes 

    accepts_nested_attributes_for :jobs, allow_destroy: true 
end 

class User < ActiveRecord::Base 

    has_one :profile 
    attr_accessible :username,:email, :password,:profile_attributes 
    accepts_nested_attributes_for :profile, allow_destroy: true 
end 

class Job < ActiveRecord::Base 

    belongs_to :profile 
    belongs_to :country 

    attr_accessible :company, :country_id, :end_date, :job_title, :profile_id, :start_date 
end 

現在,我想讓用戶能夠編輯他的個人資料並將作業添加到他的個人資料中。要做到這一點我已經使用這個代碼:

<%= f.fields_for :jobs do |j| %> 
      <%= j.label :job_title, "Job Title" %> 
      <%= j.text_field :job_title %> 

      <%= j.label :company, "Company" %> 
      <%= j.text_field :company %> 
      ............................ 
<% end %> 

但事實是,這隻能說明我的字段,如果用戶已經有了一個工作,他的個人資料,和我能夠更新。但在這種情況下,數組是空的,不會有迭代。我可以用什麼來代替這個,即使用戶沒有工作,也要確保表單出現?

我試圖添加「開始 - 結束」,但它沒有奏效。既不檢查:作業數組是空的,並創建一個新的工作對象沒有工作......或至少我的嘗試。

你有什麼想法嗎?

謝謝!

控制器中的新方法。

def new 

    resource = build_resource({}) 
    profile = resource.build_profile 
    profile.jobs += [profile.jobs.build] 
    respond_with resource 

end` 

回答

7

如果你想包括一個全新的領域Job,將其添加到jobs陣列,同時在你的控制器是:

profile.jobs.build 

在我們經常建立以同樣的方式我們的new行動中的虛擬記錄傳遞給form_for,我們也要爲fields_for建立虛擬記錄。

+0

我已編輯後添加在控制器中的新方法。還是行不通。 – user1894933 2013-03-12 01:54:01

-1

嘗試改變:
accepts_nested_attributes_for:簡檔,allow_destroy:真

TO

accepts_nested_attributes_for:簡檔,:update_only =>真

+0

仍然無法正常工作。 :| – user1894933 2013-03-12 09:08:55