我们有两个型号&连接模型:
#app/models/message.rb Class Message < ActiveRecord::Base has_many :image_messages has_many :images,through: :image_messages end #app/models/image.rb Class Image < ActiveRecord::Base has_many :image_messages has_many :messages,through: :image_messages end #app/models/image_message.rb Class ImageMessage < ActiveRecord::Base belongs_to :image belongs_to :message end
额外属性
我们希望从连接模型(ImageMessage)中提取额外的属性,并在Message模型中访问它们:
@message.image_messages.first.caption # -> what happens now @message.images.first.caption #-> we want
我们已经在声明关联时使用select方法实现了这一点:
#app/models/message.rb has_many :images,-> { select("#{Image.table_name}.*","#{ImageMessage.table_name}.caption AS caption") },class_name: 'Image',through: :image_messages,dependent: :destroy
代表
我们刚刚找到了delegate
方法,它完全符合这个需要.但是,它似乎只适用于has_one和belongs_to关联
我们刚刚使用单个关联工作,但它似乎不适用于集合(只是带你到一个公共方法)
题
您知道我们可以通过Image模型从ImageMessage连接模型返回.caption属性吗?
我们目前有这个:
#app/models/image.rb Class Message < ActiveRecord::Base has_many :image_messages has_many :messages,through: :image_messages delegate :caption,to: :image_messages,allow_nil: true end #app/models/image_message.rb Class ImageMessage < ActiveRecord::Base belongs_to :image belongs_to :message def self.caption # -> only works with class method #what do we put here? end end
更新
感谢Billy Chan(针对实例方法的想法),我们已经初步尝试了它:
#app/models/image.rb Class Image < ActiveRecord::Base #Caption def caption self.image_messages.to_a end end #app/views/messages/show.html.erb <%= @message.images.each_with_index do |i,index| %> <%= i.caption[index][:caption] %> #-> works,but super sketchy <% end %>
有什么方法可以重构,特别是为了让每次调用.caption都能得到它,它会返回特定记录的image_message.caption值吗?