繁体   English   中英

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

[英]Need help converting SQL Query to Ruby.

我是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

请给我一些想法。

您可以使用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)

我要做的是has_many through: UserUrl之间的连接创建has_many through: ,然后为Url创建一个范围以获取marked_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

注意:可能需要进行一些调整,因此,如果您在执行过程中遇到任何问题,请告诉我,我们将更新答案。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM