如何使用某种条件基于用户信息显示帖子

时间:2018-06-08 11:45:06

标签: javascript ruby ruby-on-rails-5

在我的rails应用程序中,我创建了一个配置文件用户系统,其中要发布的用户必须从他们所居住的城市列表中选择一个城市。在我的帖子模型中,我添加了belongs_to:user

class Post < ApplicationRecord
    has_attached_file :image, styles: { large: "300x300>", medium: "300x300>", thumb: "100x100>" }
    validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
    belongs_to :user
    delegate :city, :to => :user
    searchkick text_start: [:title]
    belongs_to :category
    has_many :reviews
end

在用户模型中我还添加了很多:帖子。

class User < ApplicationRecord
    has_attached_file :avatar, styles: { medium: '152x152#' }
validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/
has_attached_file :banner, styles: { large: "500x500>", medium: "300x300>", thumb: "100x100>" }
    validates_attachment_content_type :banner, content_type: /\Aimage\/.*\z/
    has_many :posts
    has_many :reviews
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

现在的问题是我试图在与post.user.city所属的城市对应的不同页面上以不同方式显示来自每个城市或特定城市的用户发布的所有帖子。

我究竟如何查询加拿大用户的帖子,例如。 在我的控制器中我尝试过:

@posts = Post.user.where(“city:canada”)

相信我没有用,因为我对rails很新,我非常喜欢rails的工作方式。

我希望有任何帮助或提示来解决这个问题。感谢

3 个答案:

答案 0 :(得分:1)

试试吧

@posts = Post.joins(:user).where("users.city = (?)", 'canada')

答案 1 :(得分:0)

@posts = Post.joins(:user).where(users: {city: 'Canada'})

答案 2 :(得分:0)

这就是我所做的并且有效:

创建了一个城市模型并将belongs_to:city添加到用户模型,就像@Crisgm指示的那样:

class City < ApplicationRecord
  has_many :users
  has_many :posts, through: :users
end

class User < ApplicationRecord
  ....
  belongs_to :city
  ....
end

这没有用:

City.find_by(name: 'Canada').posts

然而,@ Vijayakumar的想法在我的控制器上工作:

@posts = Post.joins(:user).where("users.city = (?)", 'canada')