【问题标题】:How do I create two relationships to the same model with different names?如何为具有不同名称的同一模型创建两个关系?
【发布时间】:2013-11-12 20:27:09
【问题描述】:

我有两个 Rails 4 模型:Journey 和 Place。我想要一个旅程二有两个领域,起点和目的地,它们都是地方。我的 Journey 课程如下所示:

class Journey < ActiveRecord::Base
  has_one :origin, class_name: :place
  has_one :destination, class_name: :place
end

首先,我的 Place 课程中还需要一些东西吗?我以为我需要两个“has_many”声明,但给定两个引用我无法计算出语法。

其次,是否可以使用“j.Origin”之类的语法来引用旅程的起源地点,其中“j”是旅程记录? (对于目的地也是如此。)

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 rails-models


    【解决方案1】:

    理论上,这些关系应该适合你:

    class Journey < ActiveRecord::Base
      belongs_to :origin,      class_name: :place
      belongs_to :destination, class_name: :place
    end
    
    class Place < ActiveRecord::Base
      has_many :origin_journeys,      foreign_key: origin_id,      class_name: :journey
      has_many :destination_journeys, foreign_key: destination_id, class_name: :journey
    
      def all_journeys
        Journey.where("origin_id = :place_id OR destination_id = :place_id", place_id: self.id)
      end
    end
    

    用法:

    # controller for exemple
    def journeys_of_that_place
      @place = Place.find(params[:id])
      @journeys = @place.all_journeys
      @having_this_place_as_origin = @place.origin_journeys
    end
    
    # Question 2: Yes, it is possible
    def update_origin
      @journey = Journey.find(params[:id])
      @journey.origin = Place.find(params[:place_id])
      @journey.save
    end
    

    【讨论】:

      【解决方案2】:

      回答您的问题:

      1. 除非您希望能够从 Place 访问 Journey 记录,否则您不需要 Place 类中的任何内容。但是,您需要在 places 表上使用外键 journey_id

        如果您认为可能需要它们,我会考虑在 Place 上设置范围,以返回在该位置开始或结束的 Journey 对象。查看has_onebelongs_to 上的docs

      2. 是的。这就是协会存在的目的。 This SO question 也可能有助于阐明这一点。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-28
        • 2015-12-04
        • 1970-01-01
        • 1970-01-01
        • 2021-11-26
        • 2021-01-18
        • 1970-01-01
        • 2020-06-27
        相关资源
        最近更新 更多