rails has_many manager

﹥>﹥吖頭↗ 提交于 2019-12-24 05:47:13

问题


I'm attempting to create a polymorphic imaging system which would allow various objects to have a cover image and additional images. Would I be correct in creating an Image model with belongs_to :imageable ? Or, should I separate out my logic so each model that will inherit image capabilities be given a separate polymorphic associations for both cover images and additional images?

Then, once I have setup has_many relationship, how do I manage it? In a perfect world I would want to be able to call @object.images.cover? and @object.images.additionals.


回答1:


Create an images table for your polymorphic association that has a cover boolean field, indicating if the image in the record is a cover image:

create_table :images do |t|
  t.boolean :cover, :default => false
  t.references :imageable, :polymorphic => true
  t.timestamps
end

Then include has_many :images, :as => :imageable on your objects. Now to have the @object.cover and @object.additionals that you desire, you have two options. The first is to create a Concern module to mix-in to your Object classes. The second is to subclass. I'll talk about the Concern approach here because it is a method being pushed in Rails 4, and subclassing is already familiar to most programmers.

Create a module inside app/models/concerns:

module Imageable
  extend ActiveSupport::Concern

  included do
    has_many :images, :as => :imageable # remove this from your model file
  end

  def cover
    images.where(:cover => true).first
  end

  def additionals
    images.where(:cover => false).all
  end
end

You can now mix-in this concern to your object classes. For example:

class Object1 < ActiveRecord::Base
  include Imageable

  ...
end

You will also have to include your concerns from app/models/concerns, since they won't be loaded automatically (in Rails 4, any file in that directory will be included by default).



来源:https://stackoverflow.com/questions/14541248/rails-has-many-manager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!