一种更新多个模型的表格



我正在尝试构建一种表单,该表单允许用户创建一个新帖子,该帖子的标签和该标签的tagtype,所有这些都带有一个提交按钮。

我的模型设置如下:

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

在表单所在的页面控制器中,我的方法定义如下:

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

我的表单显示仅包括帖子和标签方法,如:

<%= 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 %>

但是,当我添加fields_for(@tag_type)时,

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

我获得了nilclass的未定义方法"模型名称":class

我对Rails很新,我的猜测是它与标签属于tag_types的事实有关(而帖子has_many标签)。如果有人知道修复程序,那将不胜感激。谢谢。

您可以使用rails嵌套属性http://api.rubyonrails.org/classes/classes/activerecord/nestedattributes/classmethods.html或创建一个表单对象http://blog.codeclimate.com/blog/2012/10/17/7-ways to Decompose-fat-activerecord-models/

最新更新