使用嵌套表单创建对象 - 如何将params传递给控制器

时间:2015-11-06 13:17:15

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

我真的很挣扎如何让表单创建一个对象和两个子对象。我的指南has_one City_obj和has_one Country_obj。

guide.rb

class Guide < ActiveRecord::Base
  has_one :city_obj, dependent: :destroy
  has_one :country_obj, dependent: :destroy
  belongs_to :user
  has_many :guide_pics, dependent: :destroy

  accepts_nested_attributes_for :city_obj, :country_obj
end

city_obj.rb

class CityObj < ActiveRecord::Base
  belongs_to :guide
  belongs_to :country_obj
end

country_obj.rb

class CountryObj < ActiveRecord::Base
  belongs_to :guides
  has_many :city_obj, dependent: :destroy
end

new.html

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

  <%= render 'new_form_part', f: f, field: 'name', label: 'name', type: 'text_field', 

  <%= f.fields_for :country_obj, @guide.country_obj do |p| %>
    <%= f.text_field :name, class: 'form-control' %>
  <% end %>

  <%= f.fields_for :city_obj, @guide.city_obj do |p| %>
    <%= f.text_field :name, class: 'form-control' %>
  <% end %>
<% end %>

在我的控制器创建方法中,我得到了

params[:guide] = {"name"="whatever is submitted for city"}

那是因为设置的部分:名称被下面的text_fields覆盖。我怎样才能让他们通过params [:guide] [:city_obj] [:name]和params [:guide] [:country_obj] [:name]?

更新:有一个错字。我应该使用p.text_field,而不是f.text_field

0 个答案:

没有答案