【问题标题】:Sunspot search has_one association, other model has no foreign key太阳黑子搜索has_one关联,其他模型没有外键
【发布时间】:2013-03-11 18:07:02
【问题描述】:

我正在使用 Sunspot Solr 搜索事件,每个事件都有一个 group_id 引用一个 Group 对象(多个事件可以有同一个组)。如果用户搜索组名,我想找到正确的事件。

在可搜索块中尝试的解决方案

string :events_group_name do
  group.map(&:name)
end

错误

SQLite3::SQLException: 没有这样的列:groups.event_id: SELECT "groups".* FROM "groups" WHERE "groups"."event_id" = 3 LIMIT 1

问题是 Group 中没有 event_id,那么我怎样才能让它工作呢?解决方法是将组名保存为 Event 对象中的一列,但肯定有更好的方法。谢谢!

【问题讨论】:

    标签: ruby-on-rails sunspot sunspot-rails


    【解决方案1】:

    我对太阳黑子一无所知,但我相信您的模型映射不正确。如果您有这样的关联:

    1 个组 -> N 个事件

    您应该在模型中使用has_manybelongs_tohas_one 仅用于关联 1 到 1。在您的情况下:

    class Group
      has_many :events
      #...
    end
    
    class Event
      belongs_to :group
      #...
    end
    

    Rails 指南有一个good article 关于 Active Record 与示例的关联。你可以看看。

    【讨论】:

    • 非常感谢!我想通了,首先我们根据您的建议将其更改为 belongs_to(愚蠢的我),然后在可搜索的块中添加文本:group do group.name if group end(检查 group 是否为 nil)
    猜你喜欢
    • 2014-05-30
    • 2015-01-23
    • 2012-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多