简体   繁体   中英

How to search in an array of objects in Ruby on Rails?

This is the structure of my database in Ruby on Rails:

user have many notes
notes have many categories
categories have many notes

I have setup this relationship with has_many :through. I use

current_user.notes

to get the notes belonging to the user. But what is the best way to get the notes belonging to the current user that have a certain category? Am I supposed to use find methods like I would on a model? Thanks for reading.

I believe it should be:

current_user.notes.all(:joins => :categories, :conditions => ["categories.name = ?", search_parameter])

Just a note that this will perform a query with an INNER JOIN to use a LEFT JOIN , you should use :include :

current_user.notes.all(:include => :categories, :conditions => ["categories.name = ?", search_parameter])
class User < ActiveRecord::Base 
   has_many :notes  
   has_many :categories, :through => :notes 
end 

class Note < ActiveRecord::Base
  belongs_to :user
  belongs_to :category
end 

class Category < ActiveRecord::Base 
    has_many :notes  
end 

@current_user.notes.all

I think ,You should break your many to many relationship between notes and categories.

you could add a named_scope to notes

  named_scope :with_categories, 
              lambda{|cat|
                { 
                  :joins => [:categories],
                  :conditions => ["categories.id IN (?)", cat]
                }
              }

and then you can simply use

current_user.notes.with_categories(1, 2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM