0

I'm trying to build a form that allows a user to create a new Post, a Tag for that post, and a TagType for that tag, all with one submit button.

My models are set up as follows:

class Post < ActiveRecord::Base
belongs_to :user
has_many :post_tag_relationships, dependent: :destroy
has_many :tags, through: :post_tag_relationships
.
.
end

class Tag < ActiveRecord::Base
has_many :reverse_post_tag_relationships, class_name: "PostTagRelationship"
has_many :posts, through: :reverse_post_tag_relationships, 
                    class_name: "PostTagRelationship"
belongs_to :tag_type
.
.
end

class TagType < ActiveRecord::Base
has_many :tags
.
.
end

In the page controller where the form is located, I have the methods defined as follows:

@post = current_user.posts.build
@tag = @post.tags.build
@tag_type = @tag.tag_type.build

My form displays just fine if I only include the post and tag methods, as in:

<%= form_for(@post) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_area :content, placeholder: "Compose new post..." %>
</div>

<%= fields_for(@tag) do |u| %>
<div class="field">
<%= u.text_area :name, placeholder: "Tag" %>
</div>
<% end %>

<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>

But when I add fields_for(@tag_type), with:

<%= fields_for(@tag_type) do |y| %>
<div class="field">
<%= y.select :name %>
</div>
<% end %>

I get an undefined method 'model name' for NilClass:Class

I'm pretty new with Rails, and my guess is that it has something to do with the fact that a tag belongs_to tag_types (whereas a post has_many tags). If anyone knows a fix, it would be much appreciated. Thanks.

camt89
  • 3
  • 2

1 Answers1

4

You can use rails nested attributes http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html or create a form object http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/

bridiver
  • 1,694
  • 12
  • 13
  • Cool. A follow-up question: In the examples of nesting, accepts_nest_attributes_for is always in the model that has_one or has_many of the other model. Can my tag model accept nested attributes for tag_type given that a tag belongs_to a tag_type? – camt89 Feb 04 '14 at 05:59
  • http://stackoverflow.com/questions/7365895/does-accepts-nested-attributes-for-work-with-belongs-to - but I would lean towards a form object. – bridiver Feb 04 '14 at 12:33