嵌套的模型表单字段未显示

时间:2014-05-27 00:44:42

标签: ruby-on-rails forms nested-attributes

我在作业和地址之间有一个has_many belongs_to关系

class Job < ActiveRecord::Base
has_many :addresses
accepts_nested_attributes_for :addresses
end

class Address < ActiveRecord::Base
belongs_to :job
end

在Job表单中,我插入了正确的文本字段:

  <%= f.fields_for :addresses do |address| %>
  <%= address.label :label, "Label" %>
  <%= address.text_field :label %>

  <%= address.label :addy, "Address" %>
  <%= address.text_field :addy %>

  <%= address.label :apt, "Apt/Suite/etc" %>
  <%= address.text_field :apt %>

  <%= address.label :city, "City" %>
  <%= address.text_field :city %>

  <%= address.label :state, "State" %>
  <%= address.text_field :state %>

  <%= address.label :zip, "Zip code" %>
  <%= address.text_field :zip %>

  <% end %>

但是这些字段没有出现。我错过了什么吗?

编辑:从作业控制器添加了创建操作

def create
@job = Job.new(job_params)
@job.addresses.build
@job.user_id = current_user.id

if @job.save 
    render 'show'
else
    render 'new'
end

end

1 个答案:

答案 0 :(得分:0)

Controller看起来像什么?您是否正在构建Job的地址?

例如,您需要在控制器的new操作中执行以下操作:

def new
   @job = Job.new
   @job.addresses.build
end

我希望这会有所帮助。