如何使用form_for在rails 4中创建嵌套资源

时间:2015-03-19 16:35:08

标签: ruby-on-rails ruby-on-rails-4

company.rb

class Company < ActiveRecord::Base
  has_many :jobs, dependent: :destroy
end

job.rb

class Job < ActiveRecord::Base
  belongs_to :company
end

的routes.rb

resources :companies do
     resources :jobs
end

我想使用form_for创建一个新工作,所以我这样做:

<%= form_for(@company_job do |f| %>
...
<% end %> 

<%= form_for(:company_job, url: company_jobs_path do |f| %>
...
<% end %> 

但他们都得到错误:

Routing Error
No route matches [POST] "/jobs"

如何将表单发布到/company_jobs_path (url like this /companys/:company_id/jobs(.:format))

感谢您的回答!

1 个答案:

答案 0 :(得分:0)

视图:

form_for @company do |f|
  # company fields go here
  f.fields_for :jobs do |f2|
    # job fields go here
  end
end

模型:

class Company < ActiveRecord::Base
  has_many :jobs, dependent: :destroy
  accepts_nested_attributes_for :jobs
end