rails has_many经理 [英] rails has_many manager
问题描述
我正在尝试创建一个多态成像系统,该系统将允许各种对象具有封面图像和其他图像.用belongs_to :imageable
创建Image
模型是否正确?还是我应该分离出逻辑,以便为每个将继承图像功能的模型赋予封面图像和其他图像一个单独的多态关联?
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?
然后,一旦我设置了has_many关系,我该如何管理它?在理想的世界中,我希望能够调用@object.images.cover?
和@object.images.additionals
.
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
.
推荐答案
为具有cover
布尔字段的多态关联创建images
表,指示记录中的图像是否是封面图像:>
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
然后在对象上包含has_many :images, :as => :imageable
.现在,有了您想要的@object.cover
和@object.additionals
,您有两个选择.首先是创建一个关注模块以混入您的Object类.第二个是子类化.我将在这里讨论Concern方法,因为它是Rails 4中使用的一种方法,并且大多数程序员已经很熟悉子类化.
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.
在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
您还必须包括来自app/models/concerns
的问题,因为它们不会自动加载(在Rails 4中,默认情况下将包括该目录中的任何文件).
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).
这篇关于rails has_many经理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!