0

以下は私のモデルです。言葉で説明すると、「ショー」には「クルー」がいます。「クルー」は「人」から成り立っています。「Crew」の「Show」と「People」の間の関連付けは、タイプ「Actor」または「Other」のいずれかです。「俳優」フィールドまたは「その他」フィールドに「人」が入力されている「表示」フォームのオートコンプリート UI からトークンが送られてきます。

質問: 「Show」モデルのactor_tokens=(ids)andactor_tokens=(ids)メソッドで、入ってくるトークンを保存していますが、関係を「actor」または「other」として保存するにはどうすればよいですか??

から保存されたすべての関連付けactor_tokens=(ids)はタイプ「actor」であるother_tokens=(ids)必要があり、保存されたすべての関連付けはタイプ「other」である必要があります。

*collection_singular_ids=ids* を使用してトークンを保存するのに適したエレガントなソリューションを探しています。

クルーモデル

class Crew < ActiveRecord::Base
  belongs_to :show
  belongs_to :person

  attr_accessor  :type    #this can be 'actor'  'other' string

end

人物モデル

class Person < ActiveRecord::Base
          attr_accessible :first_name, :handle, :last_name
          has_many :crews
          has_many :shows, :through => :crews

        end

モデルを表示

 class Show < ActiveRecord::Base
      attr_accessible :handle, :name, :crew_tokens
      has_many :crews
      has_many :people, :through => :crews

      attr_reader :actor_tokens

      def actor_tokens=(ids)
        self.person_ids = ids.split(",")
            #----->associate tokens coming in here as type = 'actor'
      end

      def other_tokens=(ids)
        self.person_ids = ids.split(",")
            #----->associate tokens coming in here as type = 'other'
      end

    end 

PS: この投稿のより良いタイトルを提案してください!

ありがとう!

4

1 に答える 1

1

collection_singular_ids=を使用して、希望どおりに新しいCrewインスタンスを作成することはできません。ids_writer有効な既存の ID のリストのみを受け入れます。このメソッドで他の属性を指定することはできません。

代わりに、必要に応じてとをCrew指定してインスタンスを構築し、それらを のインスタンスに関連付けることができます。:person_id:typeShow

def actor_tokens(ids)
  create_crews_from_ids(ids, :actor)
end

def other_tokens=(ids)
  create_crews_from_ids(ids, :other)
end

  private

  def create_crews_from_ids(ids, type)
    ids = ids.split(",").each do |id|
      crews.create({ person_id: id, type: type })
    end
  end
于 2012-08-30T01:16:50.233 に答える