0

ユーザープロファイルを公開する必要があります。ユーザーは、何を表示し、何を表示しないかを選択できます。私のデザインは次のとおりです。

class Report < ActiveRecord::Base
  belongs_to :user_data
  belongs_to :report_config
  delegate :show_name, :show_address, :to => :report_config
  delegate :name, :address, :to => :user_data
  def filter_data
    report = self.user_data
    report.name = nil if show_name.false?
    report.address = nil if show_address.false?
    return report
  end
end


class UserData  < ActiveRecord::Base
 has_many :report
end

class ReportConfig  < ActiveRecord::Base
  has_many :report
end

filter_dataただし、 Report オブジェクトを呼び出すと子オブジェクトが返されるため、これはあまり良い設計ではありません。Report子オブジェクトのすべての属性を許可するにはどうすればよいですか?

継承を考えています (つまり、Report は UserData と ReportConfig を継承していますが、うまくいきません)。私の問題に適合する可能性のある他の設計パターンは何ですか?

4

1 に答える 1

1

Rubyのメタプログラミングで、ユーザーモデルのすべての属性を委任できます。

class Report < ActiveRecord::Base
  belongs_to :user_data
  belongs_to :report_config
  delegate :show_name, :show_address, :to => :report_config

  self.class_eval do
    #reject the attributes what you don't want to delegate
    UserData.new.attribute_names.reject { |n| %w(id created_at updated_at).include?(n) }.each do |n|
      delegate n , to: :user_data
    end
  end

  def filter_data    
    name = nil if show_name.false?
    address = nil if show_address.false?    
  end
end

それを使用するときは、レポートを初期化するだけです:

report = Report.find_by_user_data_id(YOUR USER DATA ID)
report.filter_data

report.name
report.address
report.....

一方、レポートオブジェクトは本当に必要ですか? UserData と ReportConfig を使用するだけではどうですか?

class UserData  < ActiveRecord::Base
  belongs_to :report_config
  delegate :show_name, :show_address, :to => :report_config

  def report_name
    name if show_name
  end

  def report_address
    address if show_address
  end      
end

class ReportConfig  < ActiveRecord::Base

end

詳細な要件がわからず、オプションを提供しようとしています。それが役に立てば幸い :)

于 2013-08-16T05:34:57.837 に答える