加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails包含范围

发布时间:2020-12-16 20:02:41 所属栏目:百科 来源:网络整理
导读:我有一个叫做作者的模型.作者有很多文章. 文章有一个称为.published的范围,它的作用是:where(published:true). 我想加载作者,发表文章. 我试过了: Author.includes(:articles.published).find(params[:author_id]) 但是会抛出一个错误:undefined方法’pu
我有一个叫做作者的模型.作者有很多文章.
文章有一个称为.published的范围,它的作用是:where(published:true).

我想加载作者,发表文章.
我试过了:

Author.includes(:articles.published).find(params[:author_id])

但是会抛出一个错误:undefined方法’published’.
任何想法?

解决方法

我认为最好的解决办法是:
Author.includes(:articles).where(:articles=>{published: true}).find(params[:author_id])

或者你可以创建范围:

class Author < ActiveRecord::Base 
    scope :published_articles,-> { includes(:articles).where(articles: { published: true}) }
end

接着:

Author.published_articles.find(params[:author_id].to_s)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读