【问题标题】:Ruby on Rails SQL Query Returns #<ActiveRecord::Relation:Ruby on Rails SQL 查询返回 #<ActiveRecord::Relation:
【发布时间】:2012-04-19 22:17:08
【问题描述】:

我在 Ruby on Rails 中构建了一个小型 Twitter 克隆。它有一个用户模型、一个微博模型和一个关系模型。关系模型存储关注的用户 ID 和相应的关注用户 ID。我正在尝试添加一个新按钮,使当前用户在他们的微帖子中使用匹配参数关注所有其他用户。我已将该参数添加到 micropost 模型中。问题是,当我在 micropost 模型中查询数据库以查找具有匹配参数的用户时,它返回

#<ActiveRecord::Relation:...

为什么要这样做?

这是包含按钮的表单代码:

<%= form_for(current_user.relationships.build(:followed_id => current_user.matched_user), :remote => true) do |f| %>
<div><%= f.hidden_field :followed_id %></div>
<div class="actions"><%= f.submit "Found A Matching User - Click Here To Follow Them" %></div>
<% end %>

这是用户模型中引用的matched_user定义:

def matched_user
Micropost.matched_with(self)
end

这里是micropost模型中引用的matched_with方法。我尝试了一些不同的方法,因此我记录了每组行的每个错误。

def self.matched_with(user)         

# matched_microposts = Micropost.find_by_parameter(:parameter)
# where("user_id IN (#{matched_microposts}) OR user_id = :user_id", :user_id => user)

# ERROR: ActiveRecord::RecordNotFound in RelationshipsController#create
# Couldn't find User with id=#<ActiveRecord::Relation:0xb59c71dc>





# matched_id = Micropost.where("parameter = ?", :parameter)
# where("user_id IN (#{matched_id}) OR user_id = :user_id", :user_id => user)

# ERROR: ActiveRecord::StatementInvalid in Pages#home
# SQLite3::SQLException: unrecognized token: "#": SELECT COUNT(*) FROM "microposts"
# WHERE (user_id IN (#<ActiveRecord::Relation:0xb5b7d3b4>) OR user_id = 101)





# matched_ids = Micropost.find_by_sql "SELECT user_id FROM microposts WHERE parameter = :parameter"
# where("user_id IN (#{matched_ids})", :user_id => user)

# ERROR: ActiveRecord::RecordNotFound in RelationshipsController#create
# Couldn't find User with id=#<ActiveRecord::Relation:0xb5a38850>

end

这是我的关系控制器创建方法:

def create
@user = User.find(params[:relationship][:followed_id])
current_user.follow!(@user)
respond_to do |format|
format.html { redirect_to @user }
format.js
end
end

最后,这是我的用户模型!方法:

def follow!(followed)
relationships.create!(:followed_id => followed.id)
end

非常感谢您能提供的任何帮助。非常感谢。

【问题讨论】:

    标签: mysql sql ruby-on-rails ruby activerecord


    【解决方案1】:

    首先Model.where 返回一个关系对象,您可以将其他运算符链接到该对象(另一个.where.order 等)

    如果您想在 db 中找到一条记录,您必须使用 .first.last.all 显式关闭该链,甚至使用 .each 迭代结果

    second - 为什么要尝试使用#{matched_ids} 直接将结果插入字符串?这将在关系对象上调用#to_s,而不是正确构建要在查询中使用的这些对象的列表

    试试这个:

    where("user_id IN (?)", matched_ids)
    

    【讨论】:

      猜你喜欢
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      • 2013-09-25
      • 2012-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-10
      相关资源
      最近更新 更多