How best to associate an Address to multiple models in rails?

前端 未结 2 2157
余生分开走
余生分开走 2021-02-20 02:31

This question on SO appears to be related to my question, but I\'m not sure my question is answered by that.

An address can belong to more than one model (UserProfile an

2条回答
  •  忘了有多久
    2021-02-20 03:28

    You missed one option: have a class that contains the common behavior and add the fields to all tables. Use a composed_of aggregate to manage the data.

    class Address
      attr_accessor :line1, :line2, :city, :state, :zip
    
      def initialize(line1, line2, city, state, zip)
        @line1 = line1
      end
    end
    
    class UserProfile < ActiveRecord::Base
      composed_of :address, :mapping => %w(line1 line2 city state zip)
    end
    
    class Event < ActiveRecord::Base
      composed_of :address, :mapping => %w(line1 line2 city state zip)
    end
    

    See #composed_of in the Ruby on Rails API docs.

提交回复
热议问题