很容易的Rails的Active-记录关联问题 [英] Really easy Rails Active-Record Associations question

查看:174
本文介绍了很容易的Rails的Active-记录关联问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个型号:

class Mission < ActiveRecord::Base
    belongs_to :category
end

class Category < ActiveRecord::Base
    has_many :missions
end

和我有一个复杂的任务查找语句:

And I have a complex Mission find statement:

@missions = Mission.send(@view, level).send(@show).search(@search).paginate :page => params[:page], :order => actual_sort, :per_page => 50

我想添加到我的查询的可能性来搜索特定的类别了。
我试过,但它不工作:

I'd like to add to my query the possibility to search for a specific category too. I tried this but it does not work:

@missions = Mission.send(@view, level).send(@show).send(:category, @category).search(@search).paginate :page => params[:page], :order => actual_sort, :per_page => 50

Rails的说,任务还没有一个.category方法。你将如何解决这个问题?

Rails says that Mission has not a .category method. How would you solve this?

谢谢,
奥古斯托

Thanks, Augusto

推荐答案

OH ......我的...... GOD

OH ... MY ... GOD

您确定这是做这个的最佳方式?

Are you sure this is the best way to be doing this?

我不认为人们将能够帮助你,如果你不解释有点多,但我很怀疑,你可以不写你的说法,像这样:

I don't think people will be able to help you if you don't explain a bit more, but I highly doubt that you couldn't write your statement like so:

@missions = Mission.select("missions.level ...,category.attr ...").where(["missions.level = ? ...", level ...]).includes(:category).where(["categories.field = ?", ...]).paginate(...)

显然,省略号(...)通常是指等。

Obviously the elipses (...) mean generally etc.

这是在测试我的一个项目工作的例子:

This is a working example on one of my projects in testing:

i = Item.where("items.name like '%Coupon%'").includes(:category).where(["categories.name = ? ",'Category 2'])

这篇关于很容易的Rails的Active-记录关联问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆