【问题标题】:Rails habtm query based on a condition基于条件的 Rails habtm 查询
【发布时间】:2017-03-31 07:44:09
【问题描述】:

我有以下关联:

class ConferenceSession < ActiveRecord::Base

  has_many :conference_sessions

end


class ConferenceSession < ActiveRecord::Base

  belongs_to  :conference

  has_and_belongs_to_many  :users

end

class User < ActiveRecord::Base

  has_and_belongs_to_many :conference_sessions

end

还有一个conference_sesssions_users 表。管理员可以允许特定的人参加特定的会议。所以我想形成一个查询,每当用户登录并选择一个会议时,他应该被允许只看到管理员允许他看到的那些会话。我试过这个:

scope :visibility,
    lambda { |user_id| joins(:conference_sessions_users).where('conference_sessions_users.user_id = ?' => user_id) }

但我收到一个错误ActiveRecord::ConfigurationError: Association named 'conference_sessions_users' was not found on ConferenceSession; perhaps you misspelled it?

可能出了什么问题?

【问题讨论】:

    标签: ruby-on-rails activerecord associations has-and-belongs-to-many


    【解决方案1】:

    错误是指您范围的joins(:conference_sessions_users) 部分。对于joins 参数“给定的符号应该与关联的名称匹配。”

    您使用了在这种情况下不正确的连接表名称。

    要使用您需要的关联:joins(:user)

    如果您只想使用连接表,您可以使用字符串来定义连接:

    joins("inner join conference_sessions_users
           on conference_session_id = conference_sessions.id")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-12
      • 1970-01-01
      • 2012-08-18
      相关资源
      最近更新 更多