如何以最佳方式定义多态关系中的主要对象?

时间:2014-08-22 08:23:21

标签: ruby-on-rails ruby polymorphic-associations

我有模特:

dress.rb

class Dress < ActiveRecord::Base
  has_many :images, as: :imageable
end

publication.rb

class Publication < ActiveRecord::Base
  has_many :images, as: :imageable
end

image.rb

class Image < ActiveRecord::Base
  mount_uploader :name, ImageUploader
  belongs_to :imageable, polymorphic: true
end

我有两个想法如何写:

  1. main_image_id(:整数)添加到图像,出版物和其他模型中。也可以创建关系has_one :main_image, class_name: 'Image', foreign_key: :main_image_id。但这是不好的方法,因为这个字段需要添加到每个创建的模型中,该模型与Image具有多态关系。
  2. main(:boolean)添加到Image。每次检查是真还是假。这也是不好的方法因为表images将有未使用的字段。 谁有什么想法?

2 个答案:

答案 0 :(得分:2)

第二种方式更好。通过这种方式,您可以按此字段订购图像并制作范围。

# image.rb
  scope main, ->{where(main: true)}
# publication.rb
  scope images, ->{images.order(:main)}

@images.main #=> will give you needed result as 
@publiscations.images #=> will give you first image as main.

如果考虑额外的列,无论如何都需要添加它。那么为什么不在更有用的地方使用呢

答案 1 :(得分:0)

<强> STI

也许try STI

#app/models/asset.rb
Class Asset < ActiveRecord::Base
  mount_uploader :name, ImageUploader
end

#app/models/image.rb
Class Image < Asset
  belongs_to :imageable, polymorphic: true
  delegate :url, to: :asset #-> not used Carrierwave, so I don't know how this is done
end

#app/models/dress.rb
Class Dress < ActiveRecord::Base
   has_many :images, as :imageable
end

#app/models/publication.rb
Class Publication < ActiveRecord::Base
   has_many :images, as :imageable
end

这将使您能够调用以下内容:

#app/controllers/dresses_controller.rb
Class DressesController < ApplicationController
   def index
      @dresses = Dress.all
   end
end

#app/views/dresses/index.html.erb
<% @dresses.each do |dress| %>
   <%= dress.images.each do |image| %>
      <%= image_tag image.url %>
   <% end %>
<% end %>