我试图在包含在 link_to 中的 View 中显示来自 HABTM 关系的单个数据,但它似乎多次返回相同的结果,并且每当我添加一个帖子时它都会增加 1。
Example
It will return 'Category:Comedy', then when I create another Post with the same category it will return 'Category:Comedy Comedy' and so on.
我这辈子都不知道为什么会这样。
Category.rb
class Category < ActiveRecord::Base
has_and_belongs_to_many :posts
end
Post.rb
class Post < ActiveRecord::Base
has_and_belongs_to_many :categories
belongs_to :user
end
index.html.erb
<% post.categories.each do |category| %>
<% category.posts.each do |post| %>
<%= link_to category.name, category_path(category) %>
<% end %>
<% end %>
posts_controller.rb
def create
@post = current_user.posts.build(post_params)
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render :show, status: :created, location: @post }
else
format.html { render :new }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
任何帮助都会很棒!
谢谢
最佳答案
我不确定为什么要运行两个循环来显示类别,所以可能删除内部循环不会重复类别链接。
<% post.categories.each do |category| %>
<%= link_to category.name, category_path(category) %
<% end %>
关于ruby-on-rails - 从 HABTM 关系返回多个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29329517/