ruby-on-rails – 在Rails中使用带有has_many的委托?
我们有两个型号&连接模型:
#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 额外属性 我们希望从连接模型(ImageMes??sage)中提取额外的属性,并在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 代表 我们刚刚找到了 我们刚刚使用单个关联工作,但它似乎不适用于集合(只是带你到一个公共方法) 题 您知道我们可以通过Image模型从ImageMes??sage连接模型返回.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值吗? 解决方法
delegate只是一个简写为等效的实例方法.对所有人来说,这不是一个解决方案,甚至还有一些争论不是那么明确.
当简单委托不适合时,您可以使用实例方法. def image_message_caption 我审查并发现任何关联是不必要的是这种情况. ImageMes??sage的类方法标题更像是常量,您可以直接引用它. def image_message_caption ImageMessage.caption end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |