【问题标题】:how to get :through association values in a method?如何获得:通过方法中的关联值?
【发布时间】:2013-11-14 11:47:17
【问题描述】:

在我的一个模型中,我有这个

has_many :professionals
has_many :services, :through => :professionals

我正在尝试了解如何从服务中获取价值

我的服务模型中有 servicedescription 列。我正在使用 elasticsearch,我想索引服务模型。

def service_name
  services.map(&:service)
end

我不确定映射是否正确,我应该使用这个来获取 json:

def to_indexed_json
    to_json( 
      include: { 
        professionals: { 
          only: [:first_name, :last_name]
          },
        services: {
          only: [:service_name]
          }
        }  
      )
end

这就是我得到的

     "professionals": [
              {
                 "first_name": "Happy",
                 "last_name": "Gilmore"
              }
           ],
     "services": []

Services 得到一个空数组。如果是直通关联,是否应该包含在专业人员中?

在通过关联方面需要一些帮助以及正确的方法。

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 associations elasticsearch


    【解决方案1】:

    使用 :methods 参数将 ActiveRecord instance methods 包含到 JSON 输出中。 :only:except 使用 DB columns only

    参考:http://apidock.com/rails/ActiveRecord/Serialization/to_json

    试试这个:

    def to_indexed_json
      to_json(
        methods: [:service_name],
        include: { 
          professionals: { only: [:first_name, :last_name] }
        }
      )
    end
    

    而#service_name 应该是这样的:

    def service_name
      services.pluck(:service)
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-16
      • 2011-05-09
      • 2021-10-07
      • 2020-06-29
      • 1970-01-01
      • 1970-01-01
      • 2019-11-12
      相关资源
      最近更新 更多