【问题标题】:Incorrect user posts being displayed. (Follower & Following)显示的用户帖子不正确。 (关注者和关注者)
【发布时间】:2014-08-20 21:41:38
【问题描述】:

我正在尝试显示我关注的用户的帖子。但是,由于某种原因,我的流索引显示了来自关注我的用户的帖子。如何显示我关注的用户的帖子,而不是相反?提前谢谢你。

用户模型

has_many :following, :through => :relationships, :source => :followed
has_many :subscribed, class_name: "Relationship", foreign_key:  "follower_id"

后模型

scope :subscribed, ->(following) { where user_id: following }

关系模型

class Relationship < ActiveRecord::Base
  belongs_to :follower, class_name: "User"
  belongs_to :followed, class_name: "User"
  validates :follower_id, presence: true
  validates :followed_id, presence: true

  has_many :followed_users, through: :relationships, source: :followed

  #fields id | user_id | follower_id | created_at | updated_at
  belongs_to :user
end

流控制器

class StreamController < ApplicationController
  def index
    @posts = Post.subscribed current_user.following 
  end 
end

流索引

<div class="page-header">
  <center><strong><h1> Stream Page </h1></strong></center>
</div>

 <div id="posts" class="transitions-enabled">
  <% @posts.each do |post| %>

    <div class="box panel panel-default">
      <%= link_to image_tag(post.image.url(:medium)), post %>
      <div class="panel-body">
      <%= post.description %><br/>
      <strong><%= post.user.name if post.user %></strong>
     <% end %>
    </div>
    <% end %>
    </div> 
  <% end %>
 </div>

【问题讨论】:

    标签: ruby-on-rails post ruby-on-rails-4 twitter-follow


    【解决方案1】:

    问题在于您调用的关联

    --

    协会

    您正在使用我的代码(这很棒!!) - 我认为问题在于您如何调用 relationship 关联数据

    您将能够做到这一点:

    #app/controllers/posts_controller.rb
    Class PostsController < ApplicationController
       @posts = Post.subscribed current_user.followed 
    end
    

    【讨论】:

    • 绝对!!你的代码就像一个魅力。我为此苦苦挣扎了一周。我是 ROR 的新手,所以这很棒。谢谢你。昨晚我尝试将上述代码添加到我的 Post 控制器中,但是它不起作用。我不确定自己做错了什么。
    • 不!在这种情况下,唯一重要的是关联名称 - 您是否已更改以适合我在此答案中提出的内容?
    • 我能够让它工作!我在我的用户模型中缺少 'has_many :following, :through => :relationships, :source => :followed'。再次感谢您的代码和专业知识。 :)
    • @Annette:如果这个答案对您有所帮助,请考虑将其标记为已接受,这样您和 Rich 就会获得代表,并且问题会从未回答的队列中退出......
    猜你喜欢
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2015-04-23
    • 1970-01-01
    相关资源
    最近更新 更多