Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.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
需要帮助将SQL查询转换为Ruby。_Sql_Ruby On Rails_Ruby - Fatal编程技术网

需要帮助将SQL查询转换为Ruby。

需要帮助将SQL查询转换为Ruby。,sql,ruby-on-rails,ruby,Sql,Ruby On Rails,Ruby,我是RubyonRails新手。我试图为下面的SQL查询确定正确的ruby查询。下面的查询是有效的,但我想知道最有讽刺意味的方法是什么 @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

我是RubyonRails新手。我试图为下面的SQL查询确定正确的ruby查询。下面的查询是有效的,但我想知道最有讽刺意味的方法是什么

@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

请告诉我一些想法。

您可以在rails中使用
连接
where

@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)

我要做的是在
用户
Url
之间创建一个
连接,然后为
Url
创建一个范围,以获取标记为发送的
。比如:

模型 使用
注意:这可能需要一些调整,因此如果您在实施过程中遇到任何问题,请告诉我,我将更新答案

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

#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)

精彩的!这让生活变得容易多了。谢谢
#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)