1

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

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

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

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

4

2 回答 2

2

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

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
于 2013-11-12T20:57:16.407 回答
1

要回答您的问题:

  1. 除非您Place希望能够JourneyPlace. 但是,您需要journey_idplaces表上使用外键。

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

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

于 2013-11-12T20:56:29.130 回答