【问题标题】:Filter data through rails controller通过 rails 控制器过滤数据
【发布时间】:2015-12-09 02:31:40
【问题描述】:

我需要对我的数据应用查询过滤器,以将一个表的外键与另一个表的主键匹配,我现在想通过控制器来完成。文档是主表/模型。 Keyword 是另一种模型,但也是 Document 的子表。寻找有关此语法的建议。

一个例子是:

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

keywordable_id 是来自 Document 模型/表的外键。

【问题讨论】:

    标签: mysql ruby-on-rails-4 controller models


    【解决方案1】:

    来自

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

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

    另一方面,我建议你设置关联

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

    查询@keywords = @document.keywords

    阅读更多:http://guides.rubyonrails.org/association_basics.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-11
      • 1970-01-01
      • 2013-08-09
      • 2020-05-04
      • 1970-01-01
      相关资源
      最近更新 更多