복붙노트

[RUBY-ON-RAILS] has_many를 들어 범위 지정을 레일 :에 대한 액세스 추가 데이터를 통해

RUBY-ON-RAILS

has_many를 들어 범위 지정을 레일 :에 대한 액세스 추가 데이터를 통해

우리가 알다시피, 레일에 당신은 당신의 has_many에 추가 속성을 추가 할 수 있습니다 모델을 결합을 통해

(가) 모델을 결합 및 그것으로보기를 채울에서 나는 여분의 데이터를 추출하고 싶습니다. 내가 직접 모델을 결합 참조하여이 작업을 가지고,하지만 난 이런 식으로, 현재 항목에 관련 가입 모델 데이터를 추가하고 싶습니다 :

#app/models/message.rb
    #Images
    has_many :image_messages, :class_name => 'ImageMessage'
    has_many :images, :class_name => 'Image', :through => :image_messages, dependent: :destroy

   #app/views/messages/show.html.erb
   <%= @message.image_messages.first.caption %> #-> works

   #app/views/messages/show.html.erb
   <%= @message.images.first.caption %> #-> what I'd like to happen

특히,이 같은 자막이 image_messages에 저장되는로, 특정 이미지의 캡션을 호출 할 수있는 모델을 조인해야합니다 :

#image_messages join table
id | message_id | image_id | caption | created_at | updated_at

내가 본 바로는,이에 대한 범위를 사용할 수 있습니다,하지만 난 모르겠어요 수

어떤 도움을 주시면 감사합니다! 나는 당신이 자주하지 않는 그 중 하나이기 때문에이 질문을 거라고 생각!

해결법

  1. ==============================

    1.사실이에 해결책을 발견

    사실이에 해결책을 발견

    내가 관리하는 SQL SELECT 문에 마법의 거짓말이 RailsCast에 대해 알아보십시오

    특히, 테이블에서 표준 SELECT *과 함께, 당신은 다른 함수를 정의 할 수 있으며, AS 기능을 원래 쿼리에 첨부

    이 코드이었다 무엇을 가지고 그래서 :

    #Images
        has_many :image_messages, :class_name => 'ImageMessage'
        has_many :images, -> { select("#{Image.table_name}.*, #{ImageMessage.table_name}.caption AS caption") }, :class_name => 'Image', :through => :image_messages, dependent: :destroy
    

    이 훌륭하게 작동 - 이렇게하면 image.caption @ 호출 할 수 있도록 이미지 객체에 이미지의 "자막"을 첨부 할 수 있습니다!

  2. from https://stackoverflow.com/questions/20250636/rails-scoping-for-has-many-through-to-access-extra-data by cc-by-sa and MIT license