【问题标题】:Rails fields_for not showing upRails fields_for 未显示
【发布时间】:2013-03-12 01:15:51
【问题描述】:

我被困住了。 我有以下模型:个人资料、用户、工作。

用户有一个个人资料,个人资料有很多工作。

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`

【问题讨论】:

    标签: ruby-on-rails ruby forms fields-for


    【解决方案1】:

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

    profile.jobs.build
    

    就像我们经常在 new 操作中建立一个虚拟记录以传递给 form_for 一样,我们也必须为 fields_for 建立一个虚拟记录。

    【讨论】:

    • 我已经编辑了在控制器中添加新方法的帖子。还是不行。
    【解决方案2】:

    尝试改变:
    accept_nested_attributes_for :profile, allow_destroy: true

    accepts_nested_attributes_for :profile, :update_only => true

    【讨论】:

      猜你喜欢
      • 2013-06-15
      • 2012-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多