Rails fields_for没有显示

时间:2013-03-12 01:15:51

标签: ruby-on-rails ruby forms 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 %>

但问题是,如果用户已经在他的个人资料中找到了工作,这只会向我显示字段,并且我能够更新它。但在这种情况下,数组是空的,不会有迭代。即使用户没有工作,我还能用什么代替呢?确保表格出现?

我尝试添加“开始 - 结束时”,但它不起作用。既不检查:jobs数组是否为空并且创建新的Job对象不起作用...或者至少我的尝试。

你有什么想法吗?

谢谢!

控制器中的新方法。

def new

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

end`

2 个答案:

答案 0 :(得分:7)

如果您想要为全新的Job添加字段,请在控制器中添加jobs数组:

profile.jobs.build

与我们经常在new动作中构建虚拟记录以传递给form_for的方式相同,我们也需要为fields_for构建虚拟记录。

答案 1 :(得分:-1)

尝试更改:
accepts_nested_attributes_for:profile,allow_destroy:true

TO

accepts_nested_attributes_for:profile,:update_only =&gt;真