10

我可以在Rails中這樣做嗎?與attr_accessible,has_one,has_many混合模塊

module Authored 
    belongs_to :user 
    attr_accessible creation_date 
end 

class Line < ActiveRecord::Base 
    include Authored 
end 

class Document < ActiveRecord::Base 
    include Authored 
end 

class User < ActiveRecord::Base 
    has_many :creations, :class_name => 'Authored' 
end 

或者我是否需要使用簡單繼承,即使我的創作類具有不同的類層次結構?

回答

23
module Authored 
    extend ActiveSupport::Concern 

    included do 
    belongs_to :user 
    attr_accessible :creation_date 
    end 
end 

class Line < ActiveRecord::Base 
    include Authored 
end 

class Document < ActiveRecord::Base 
    include Authored 
end 

有關ActiveSupport::Concern更多信息,http://api.rubyonrails.org/classes/ActiveSupport/Concern.html

+1

正是我需要的,謝謝:)好像它不會在我的用戶的has_many鍛鍊。我可能需要使用多態關聯來處理它。 –