use*_*933 1 ruby forms ruby-on-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
Run Code Online (Sandbox Code Playgroud)
现在,我希望用户能够编辑他的个人资料并将作业添加到他的个人资料中.为此,我使用了以下代码:
<%= 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 %>
Run Code Online (Sandbox Code Playgroud)
但问题是,如果用户已经在他的个人资料中找到了工作,这只会向我显示字段,并且我能够更新它.但在这种情况下,数组是空的,不会有迭代.我可以使用什么而不是这个,以确保表格即使用户没有工作也会出现?
我试图添加"开始 - 结束时",但它没有用.既不检查:jobs数组是否为空并且创建新的Job对象不起作用...或者至少我的尝试.
你有什么想法?
谢谢!
控制器中的新方法.
def new
resource = build_resource({})
profile = resource.build_profile
profile.jobs += [profile.jobs.build]
respond_with resource
end`
Run Code Online (Sandbox Code Playgroud)
如果您想要包含全新的字段,请在控制器Job中将其添加到jobs阵列中:
profile.jobs.build
Run Code Online (Sandbox Code Playgroud)
就像我们经常在new传递给我们的动作中构建一个虚拟记录一样,我们也要form_for构建一个虚拟记录fields_for.
| 归档时间: |
|
| 查看次数: |
2240 次 |
| 最近记录: |