【问题标题】:How do I display posts based on the users information using some sort of conditions如何使用某种条件根据用户信息显示帖子
【发布时间】:2018-06-08 11:45:06
【问题描述】:

在我的 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

在用户模型中,我还添加了很多:posts。

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("城市:加拿大")

相信我,那是行不通的,因为我对 Rails 完全陌生,而且我非常喜欢 Rails 的工作原理。

我将不胜感激任何帮助或提示来解决这个问题。谢谢

【问题讨论】:

  • 但是@posts = Post.user.where(city: "canada") 有效吗?

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


【解决方案1】:

试试看

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

【讨论】:

  • 我收到此错误:NoMethodError at /pages/canada undefined method `user' for #<0xc844650>
【解决方案2】:
@posts = Post.joins(:user).where(users: {city: 'Canada'})

【讨论】:

  • 这给了我 SystemStackError。
【解决方案3】:

这就是我所做的并且成功了:

创建了一个城市模型并将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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多