0

我是 Ruby on Rails 的新手。我正在尝试为以下 SQL 查询确定正确的 ruby​​ 查询。以下查询有效,但我想知道最 Railsy 的方法是什么。

@user_urls = Url.find_by_sql(["
select urls.* 
from urls 
join connections on connections.id = urls.connection_id 
join users on users.id = connections.user_id 
where urls.marked_for_sending = true and users.id = ?", @user.id])

以下是有关我的模型关联的一些详细信息 -

User has many Connections
Connection has many URLs
Connection belongs to User
URL belongs to Connection

请给我一些想法。

4

3 回答 3

0

您可以在导轨中使用joinswhere

@user_urls = Url.joins("LEFT JOIN connections ON connections.id = urls.connection_id").joins(" LEFT JOIN users ON users.id = connections.user_id").where("urls.marked_for_sending =? AND users.id = ?", true, @user.id)
于 2013-11-01T07:48:57.503 回答
0

我要做的是在 and 之间创建一个连接has_many through:,然后为fetch创建一个范围。就像是:UserUrlUrlmarked_for_sending

楷模

class User
  has_many :connections
  has_many :urls, through: :connections
end

class Url
  scope :marked_for_sending, where(marked_for_sending: true)
end

用法

@user_urls = @user.urls.marked_for_sending

注意:可能需要一些调整,所以如果您在实施时遇到任何问题,请告诉我,我会更新答案。

于 2013-11-01T07:52:12.733 回答
0

您可以在 User 模型中添加关联:

#user.rb
has_many :urls, :through => :connections

@user_urls = @user.urls.where(marked_for_sending: true)

其他选项:

@user_urls = Url.joins(:connection).where(connections: {user: @user}).where(marked_for_sending: true)
于 2013-11-01T07:53:22.833 回答