Domanda

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top