开发者

Simple nested form, but doesn't seem to work

I'm trying to build a simple nested form, checking a lot of resources online, but can't find what is it that I'm missing! I have the following:

class Configuration < ActiveRecord::Base
  has_many :configoptions
  accepts_nested_attributes_for :configoptions
end

class Configoption < ActiveRecord::Base
  belongs_to :configuration
  has_many :items
end

Now, I'm trying to make a simple form when you select a configuration so it would show the configoptions belonging to it, but nothing works!

This is the view without any html

  <%= form_for :config do |f| %>
    <%= f.text_field(:name)%>
    <% f.fields_for @options do |option|%>
    <% end %>
  <% end %>

In the controller I have:

  def show
    @config = Configuration.find(params[:id])
    @options = @config.configoptions
  end

But i end up getting the error:

undefined method `model_name' for Array:Class开发者_高级运维

Does anyone have advice for me? Thanks a lot!


FYI, Ryan Bates (RailsCasts) has created a gem to handle much of this. I'm using it now and it works great!

See https://github.com/reu/simple_nested_form for the details.


You'll have to specify a model_name if you are using a collection (like an array).

  <%= form_for :config do |f| %>
    <%= f.text_field(:name)%>
    <%= f.fields_for :configoptions, @options do |option|%>
      <%= option.text_field(:some_attribute) %>
    <% end %>
  <% end %>

In fields_for I am passing two arguments, :configoptions as the model name and @options as the collection to use. http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html has a ton of great nested attribute examples if you scroll down just above half way.

Alternatively (and my personal preferred method) is to loop through the collection and call fields_for for each object.

  <%= form_for :config do |f| %>
    <%= f.text_field(:name)%>
    <% @options.each do |configoption| %>
      <%= f.fields_for configoption do |option|%>
        <%= option.text_field(:some_attribute) %>
      <% end %>
    <% end %>
  <% end %>


Try:

class Configuration < ActiveRecord::Base
  has_many :configoptions, :dependent => :destroy
  accepts_nested_attributes_for :configoptions, :allow_destroy => true
end


You used:

<% f.fields_for @options do |option|%>

try using

<%= f.fields_for @options do |option|%>

I had the same problem, it was solved by this trivial idea.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜