ruby on rails一个模型多个与另一个模型的关联

时间:2012-05-29 04:16:53

标签: ruby-on-rails database activerecord associations has-many

让一个模型同时具有has_manyhas_one关系的正确(Rails)方式是什么?就我而言,我希望我的Device模型能够跟踪其当前位置及其之前的所有位置。 这是我的尝试,它是功能性的,但有更好的方法吗?

模型

class Location < ActiveRecord::Base
  belongs_to :device
end

class Device < ActiveRecord::Base
  has_many :locations # all previous locations
  belongs_to :location # current location
end

5 个答案:

答案 0 :(得分:0)

class Device < ActiveRecord::Base
  has_and_belongs_to_many :locations
end

答案 1 :(得分:0)

嗯,Rails方式是你可以创建你喜欢的许多关联。您可以根据逻辑命名您的关联。只需将:class_name选项传递给关联逻辑。

class Location < ActiveRecord::Base
  belongs_to :device
end

class Device < ActiveRecord::Base
  has_many :previous_locations,
           :class_name => "Location",
           :conditions => ["locations.created_at < ?", DateTime.now]
  has_one  :location,
           :class_name => "Location",
           :conditions => ["locations.created_at = ?", DateTime.now]
end

答案 2 :(得分:0)

在“Active Record Associations指南”中,我建议阅读第2.8节:选择has_many:through和has_and_belongs_to_many

  

最简单的经验法则是你应该设置一个has_many   :如果你需要使用关系模型,通过关系   作为一个独立的实体。如果你不需要做任何事情   关系模型,设置一个可能更简单   has_and_belongs_to_many关系(虽然你需要记住   在数据库中创建连接表。)

     

你应该使用has_many:through如果你需要验证,回调,   或连接模型上的额外属性。

http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many

答案 3 :(得分:0)

class Location < ActiveRecord::Base
  belongs_to :device
end

class Device < ActiveRecord::Base
  has_many  :locations

  def previous_locations
    self.locations.order('created_at asc').limit( self.locations.count-1)
  end

  def current_location # or last_location
    self.locations.order('created_at desc').limit(1)
  end

  # you may like to add this one
  def current_location= args
    args = Location.new args unless args.is_a? Location
    self.locations << args
  end
end

请注意,所有@ device.locations,@ device.previous_locations和@ device.current_location都将返回ActiveRecord :: Relation

答案 4 :(得分:0)

class Location < ActiveRecord::Base
  belongs_to :device
  has_one :current_location, :class_name => 'Device',
                              :conditions => { :active => true }
end

class Device < ActiveRecord::Base
  has_many :locations # all previous locations
end

Location有一个名为'active'的布尔字段,您设置为true / false。