【问题标题】:Nested form not rendering Rails 3.2嵌套表单不呈现 Rails 3.2
【发布时间】:2013-05-20 17:08:36
【问题描述】:

视图中的嵌套表单不会呈现,除非我删除 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 %>

任何输入都会很棒 - 谢谢

【问题讨论】:

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


    【解决方案1】:

    发生这种情况是因为您的工作没有雇主。

    将您的代码更改为:

    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
    

    【讨论】:

    • 它现在在查看工作/新时为 nil:NilClass 抛出一个未定义的方法 `employers'
    • 感谢更新,它现在为 nil:NilClass 抛出未定义的方法 `build'
    • 为什么将它声明为belongs_to 而不是has_many。乔布斯有一个或多个雇主?
    • 更新 fields_for 符号后,它可以工作了!谢谢你。您能否解释一下 job.employer = job.build_employer 行?
    • 这一行只是创建了一个新的 Employer 并将 @job 分配给它的 jobs 字段(通过关联)。在这里阅读更多:api.rubyonrails.org/classes/ActiveRecord/Associations/…
    【解决方案2】:

    这一行:

    belongs_to :employers
    

    应该是单数:

    belongs_to :employer 
    

    使用此关联,您无需嵌套表单,您可以使用 select 为每项工作挑选雇主。

    但是,如果您的每项工作需要多个雇主,并且每个工作可以有多个雇主,请参阅screencast

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多