Rails 模型关联的查询问题

nicetyler · August 07, 2017 · Last by nicetyler replied at August 07, 2017 · 1209 hits

这个问题有点难表述清楚,是这样的,我这个 article 模型属于 type

belongs_to :type,foreign_key: "news_type_id"

然后 type 表如图所示 我想根据 class_code 的内容比如说,根据 class_code = "新闻类型",再 index 页面中显示所有的新闻 我的想法:

  1. 在查询是时候做个判断,只要新闻类型的,但是这个查询语句我不会写 目前这样写是错的 ruby @articles = Article.where(type:{class_code: "新闻类型"}).paginate(page: params[:page],per_page:8)
  2. 在显示的时候,只显示新闻类型
<% @articles.where(type.class_code: "新闻类型").each do |d| %>

这样写也是错的,想问下这样有关联的模型,怎么根据另外一个表的某个字段显示特定的内容啊

Article.joins(:type).where('types.class_code = ?', '新闻类型')
Reply to winse

非常感谢,一下就解决了,就是这样的,sql 语句就是这样

SELECT *
FROM types A
INNER JOIN t_news B ON A.id=B.news_type_id
WHERE A.class_code='新闻类型'

type 是关键词,这样用会不会留坑啊

Reply to w7938940

type 关键字是 mysql 的坑!这么设计早晚得踩上!

Reply to mystery

会出现什么问题啊

You need to Sign in before reply, if you don't have an account, please Sign up first.