0

任意のオブジェクト タイプで todo リストを作成する必要があります。リストの一部になるオブジェクト: ダイエット、処方箋、獣医相談。

私が作った1時間あたり:object_type列にオブジェクトクラスを保持し、オブジェクトを取得するときに.send(TodoItem.x.object_type)メソッドを使用します。これが最善の方法ですか?シリアル化オプションを使用することを考えましたが、方法がわかりません。

そして、このために、私はこの構造を作成します:


ダイエット(id: 整数、名前: 文字列、todo_item_id: 整数、created_at: 日時、updated_at: 日時)

class Diet < ActiveRecord::Base
  belongs_to :todo_item
end

処方箋(id:整数、名前:文字列、todo_item_id:整数、created_at:日時、updated_at:日時)

class Prescription < ActiveRecord::Base
  belongs_to :todo_item
end

TodoItem (id: 整数、名前: 文字列、done_date: 日付、is_done: ブール値、created_at: 日時、updated_at: 日時、object_type: 文字列)

class TodoItem < ActiveRecord::Base
  has_one :diet
  has_one :prescription

  def related
    self.send(self.object_type)
  end
end

コントローラーで私は:

class PrescriptionsController < ApplicationController
  before_filter :create_todo_item, only: [:create]
  def create
    @prescription = Prescription.new(prescription_params)
    @prescription.todo_item = @todo_item
    ...
  end

class ApplicationController < ActionController::Base
  def create_todo_item
    @todo_item = TodoItem.new(object_type: params[:controller].singularize)
    @todo_item.save
  end
end

下手な英語でごめんなさい :|

4

1 に答える 1

1

たぶん、別のアプローチを試すことができます:

ダイエット.rb

has_many :todo_items, as: :todoable
after_create :create_todo_item

def create_todo_item
  todo_items.create
end

処方.rb

has_many :todo_items, as: :todoable
after_create :create_todo_item

def create_todo_item
  todo_items.create
end

他のすべてのモデルでは、上記のコードを使用できます。

TodoItem.rb で行う必要があるのは、

belongs_to :todoable, polymorphic: true

そして TodoItem todoable_type と todoable_id にフィールドを作成します

IMOの方がはるかに良く見えます。この方法でも、「todoable」モジュールを作成してさらにリファクタリングし、必要なすべてのモデルにロードすることができますが、それは次のステップです

于 2013-06-13T21:32:45.370 に答える