ruby-on-rails - 从 HABTM 关系返回多个结果

标签 ruby-on-rails ruby ruby-on-rails-4 has-and-belongs-to-many

我试图在包含在 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/

相关文章:

ruby-on-rails - simple_form 未检测嵌套属性的触发验证

ruby - 在 Ruby 中获取 DNS TXT 记录

Ruby - 包括两个模块,它们都有一个同名的子模块

ruby-on-rails - 为什么 Rails 5 使用 ApplicationRecord 而不是 ActiveRecord::Base?

ruby-on-rails - 数据库中一个属性中一周的多天

ruby-on-rails - Rails json 输出载波缩略图版本

javascript - 恢复使用原型(prototype)

html - Ruby JSON 多词字符串在 HTML 中呈现不正确

ruby-on-rails - Ruby on Rails、form_remote_tag 和 Google Maps API

arrays - 从 Ruby 中的嵌套哈希和数组中提取值