需要帮助将SQL查询转换为Ruby。
我是RubyonRails新手。我试图为下面的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
@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)