Search code examples
mysqlruby-on-rails-4controllermodels

Filter data through rails controller


I need to apply a query filter to my data to match the foreign key of one table to the primary key of the other table, and I'd like to do it through the controller for now. Document is the main table/model. Keyword is another model but is also a subtable of Document. Looking for advice on syntax for this.

An example would:

@keywords = Keyword.where(keywordable_id == @document.id)

keywordable_id is the foreign key from the Document model/table.


Solution

  • from

    @keywords = Keyword.where(keywordable_id == @document.id)

    to

    @keywords = Keyword.where(keywordable_id: @document.id)

    On the other hand, I suggest you to set association

    class Document < ActiveRecord::Base
      has_many :keywords, foreign_key: 'keywordable_id'
    end
    
    class Keyword < ActiveRecord::Base
      belongs_to :document, primary_key: 'keywordable_id'
    end
    

    query @keywords = @document.keywords

    Read more: http://guides.rubyonrails.org/association_basics.html