Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/68.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,我有3种型号: class User < ActiveRecord::Base has_many :categories has_many :links, through: :categories end class Category < ActiveRecord::Base belongs_to :user has_many :links end class Link < ActiveRecord::Base belongs_to :category

我有3种型号:

class User < ActiveRecord::Base
  has_many :categories
  has_many :links, through: :categories
end

class Category < ActiveRecord::Base
  belongs_to :user
  has_many :links
end

class Link < ActiveRecord::Base
  belongs_to :category
end

但我不确定这是一个好的解决方案。如何以rails的方式实现这一点?

需要建立多对多关系

class User < ActiveRecord::Base
  has_many :categories
  has_many :links, through: :categories
end

class Category < ActiveRecord::Base
  belongs_to :user
  belongs_to :link
end

class Link < ActiveRecord::Base
  has_many :categories
  has_many :users, through: :categories
end

这很好,但由该代码生成的SQL查询类似于

SELECT * FROM links where links.user_id = ?
然后,您感兴趣的链接将通过select方法过滤。 如果您的用户有许多链接,但只有少数是收藏夹,则通过以下方式选择收藏夹可能会更有效:

@links = current_user.links.where(favorite: true)
这将生成此类查询:

SELECT * FROM links where links.user_id = ? AND links.favorite = 't'
您可以在链接模型中创建一个作用域来过滤收藏夹链接

class Links < ActiveRecord::Base
  scope :favorites, -> { where(favorite: true) }
end

这可能更有效,因为这将创建更少的活动模型对象。

要添加到
@Pierre Michard
的答案中,您可能还希望查看,它将基本上取代
链接中的
范围

#app/models/user.rb
class User < ActiveRecord::Base
   has_many :categories
   has_many :links, through: :categories do
      def favorites
         where favorite: true
      end
   end
end
class Links < ActiveRecord::Base
  scope :favorites, -> { where(favorite: true) }
end
@links = current_user.links.favorites
#app/models/user.rb
class User < ActiveRecord::Base
   has_many :categories
   has_many :links, through: :categories do
      def favorites
         where favorite: true
      end
   end
end
@links = current_user.links.favorites