Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/52.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 迷茫于有许多缺点:和使用类名的替代模式相比有很多优点_Ruby On Rails_Ruby_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails 迷茫于有许多缺点:和使用类名的替代模式相比有很多优点

Ruby on rails 迷茫于有许多缺点:和使用类名的替代模式相比有很多优点,ruby-on-rails,ruby,ruby-on-rails-4,Ruby On Rails,Ruby,Ruby On Rails 4,我现在有这个 has_many :planes, -> { where approved: true }, class_name: 'UserPlane' 我想它有点臭,但它很管用,而且很容易做。我想正确的方法应该是这样做 has_many :planes, through: :user_planes, source: :plane do def approved where('user_planes.approved = ?', true) end end h

我现在有这个

has_many :planes, -> { where approved: true },  class_name: 'UserPlane'
我想它有点臭,但它很管用,而且很容易做。我想正确的方法应该是这样做

has_many :planes, through: :user_planes, source: :plane do
   def approved
     where('user_planes.approved = ?', true)
   end
end

has_many :user_planes

因为我只想要得到批准的飞机,我不在乎没有批准的飞机。与第一种方法相比,第二种方法的优点是什么。谢谢。

这两个片段会给你不同的结果。第一个关联将从数据库返回一组
UserPlane
对象,而第二个关联将返回一组
Plane
对象。但是,您应该能够将第二个版本简化为:

has_many :user_planes, -> { where approved: true }
has_many :planes, through: :user_planes, source: :plane

哦,德普。我完全错过了。谢谢