【问题标题】:How to limit an association list based on a related model如何根据相关模型限制关联列表
【发布时间】:2016-04-20 13:14:21
【问题描述】:

我知道我应该知道这一点,但我似乎根本无法弄清楚,而且我还是开发新手......

所以我有四个模型...

约会

class Appointment < ActiveRecord::Base
    belongs_to :user
    belongs_to :profile
    belongs_to :location
end

个人资料

class Profile < ActiveRecord::Base

    belongs_to :user
    has_many :appointments

    has_many :profile_locations
    has_many :locations, through: :profile_locations
    accepts_nested_attributes_for :profile_locations, reject_if: :all_blank, allow_destroy: true
    accepts_nested_attributes_for :locations, reject_if: :all_blank, allow_destroy: true

end

profile_locations

class ProfileLocation < ActiveRecord::Base

    belongs_to :profile
    belongs_to :location
    belongs_to :location_type

    accepts_nested_attributes_for :location

end

和地点

class Location < ActiveRecord::Base

    has_many :profile_locations
    has_many :profiles, through: :profile_locations

    has_many :appointments

end

在创建约会页面上,我已经有一个相关的档案记录在案。我的 simple_form 上还有一个关联字段,用于我希望能够根据与个人资料相关的位置分配给约会的位置..

我正在尝试这样的事情,但似乎无法正常工作。

%td= f.association :location, :as => :collection_select, collection: Location.where( location.profile_location.profile_id: @profile.id ), label_method: :address_1, value_method: :id, include_blank: false, :input_html => {:class => "input-small"}, :label => "Select The Location"

我在这里遗漏了什么还是有更简单的方法来查询这个?任何有关这方面的指导都会有所帮助。

【问题讨论】:

  • 你能详细解释一下吗?

标签: ruby-on-rails ruby drop-down-menu associations


【解决方案1】:

如果您使用的是simple_form,您应该像这样创建collection_input

%td= f.input :location, collection: Location.joins(:profile_location).where(profile_locations: { profile_id: @profile.id })

【讨论】:

  • 这篇文章似乎没有像预期的那样拉它: Location.where( location.profile_location.profile_id: @profile.id ) 这是基于该类型过滤器的正确语法吗在活动的个人资料上?
  • 哦,是的。我只是复制/粘贴了您的查询。这是错误的。您需要加入profile_locations。因此它将是:Location.joins(:profile_location).where(profile_locations: { profile_id: @profile.id })。用正确的查询更新答案
【解决方案2】:

感谢 ksarunas.... 我需要进行一些小调整,但让它运行起来了!

%td= f.association :location, :as => :collection_select, collection: Location.includes(:profile_locations).where(profile_locations: { profile_id: @appointment.profile_id })

在尝试拉入@profile.id 时出错,必须在两个地方都将 profile_locationS 复数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    相关资源
    最近更新 更多