【问题标题】:Ruby on rails - Where SQL methodRuby on rails - Where SQL 方法
【发布时间】:2012-08-10 14:35:23
【问题描述】:

我想获取所有 'something' = true 的微博。

这段代码运行良好

class UsersController < ApplicationController
  .
  .
  .
  def show
    @user = User.find(params[:id])
    @microposts = @user.microposts
    @titre = @user.nom
  end
end

但是当我尝试创建 where sql 方法时,此代码不起作用。

class UsersController < ApplicationController
      .
      .
      .
      def show
        @user = User.find(params[:id])
        @microposts = @user.microposts.where("something = 'true'")
        @titre = @user.nom
      end
    end

有什么想法吗?

【问题讨论】:

标签: sql ruby-on-rails ruby-on-rails-3 activerecord


【解决方案1】:
  def show
    @user = User.find(params[:id])
    @microposts = @user.microposts.where(something: true)
    @titre = @user.nom
 end

有关缩小查询范围的更多信息,请参阅 herehere

【讨论】:

  • @user1560922 - 如果问题解决,请接受答案。谢谢
【解决方案2】:

这样写:

Micropost.where(user_id: params[:id], something: true)

【讨论】:

  • 是的,但在我的用户模型上:“has_many :microposts”将无用吗?
  • 有什么区别?也许其他地方会需要它。
  • 改成something: true是个好建议,但没有理由不使用@user.microposts
猜你喜欢
  • 2019-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-11
相关资源
最近更新 更多