嵌套表单不呈现Rails 3.2

时间:2013-05-20 17:08:37

标签: ruby-on-rails ruby-on-rails-3

除非我删除f属性,否则视图中的嵌套表单将不会呈现,在这种情况下,提交按钮将不起作用。我有两个模特,工作和雇主。我一直关注railscast here

job.rb

  attr_accessible :title, :location, :employers_attributes,     
  belongs_to :employers
  accepts_nested_attributes_for :employers

employer.rb

 attr_accessible :companyname, :url
 has_many :jobs

jobs_controller.rb

  def new

    @job = Job.new
    @employer = Employer.new
  end

_form.html

<%= form_for(@job) do |f| %>


    <%= f.label :title %>
    <%= f.text_field :title %>


    <%= f.label :location %>
    <%= f.text_field :location %>



  <%= f.fields_for :employers do |builder| %>

        <%= builder.label :companyname, "Company Name" %>
        <%= builder.text_field :companyname %>


        <%= builder.label :url, "Web Address" %>
        <%= builder.text_field :url %>

    <% end %>


  <div class="actions">
    <%= f.submit %>
  </div>

 <% end %>

任何输入都会很棒 - 谢谢

2 个答案:

答案 0 :(得分:2)

这是因为你的工作没有雇主。

将您的代码更改为:

def new
  @job = Job.new
  @job.employer = @job.build_employer
end

在你的job.rb改变:

attr_accessible :title, :location, :employer_attributes,     
belongs_to :employer
accepts_nested_attributes_for :employer

答案 1 :(得分:1)

这一行:

belongs_to :employers

应该是单身:

belongs_to :employer 

通过此关联,您不需要嵌套表单,您可以为每个作业使用select for pick雇佣。

但如果每个工作需要很多雇主,而且每个工作都有很多雇主可以看到screencast