【发布时间】:2026-02-03 09:10:01
【问题描述】:
我正在尝试构建一个表单,允许用户创建一个新帖子、该帖子的标签和该标签的 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
如果我只包含 post 和 tag 方法,我的表单就可以正常显示,如下所示:
<%= 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 很陌生,我的猜测是它与标签 belongs_to tag_types (而帖子有_many 标签)这一事实有关。如果有人知道修复程序,将不胜感激。谢谢。
【问题讨论】:
-
Rails 3? github.com/ryanb/nested_form
标签: ruby-on-rails forms models