需要帮助将SQL Query转换为Ruby。

时间:2013-11-01 07:35:49

标签: sql ruby-on-rails 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

请给我一些想法。

3 个答案:

答案 0 :(得分:0)

您可以在rails

中使用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)

答案 1 :(得分:0)

我要做的是在has_many through:User之间建立Url连接,然后为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

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

答案 2 :(得分:0)

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

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