Really easy Rails Active-Record Associations question

时光毁灭记忆、已成空白 提交于 2019-12-25 02:17:10

问题


I have 2 models:

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 says that Mission has not a .category method. How would you solve this?

Thanks, Augusto


回答1:


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'])



回答2:


try performing the where selection on category_id



来源:https://stackoverflow.com/questions/6789459/really-easy-rails-active-record-associations-question

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!