繁体   English   中英

Ruby on Rails SQL查询返回#

[英]Ruby on Rails SQL Query Returns #<ActiveRecord::Relation:

我在Ruby on Rails中构建了一个小的twitter克隆。 它具有一个用户模型,一个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

这是微职位模型中引用的match_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

非常感谢您能提供的任何帮助。 这是非常赞赏。

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

如果你想在数据库中找到一个记录你必须明确地关闭链.first.last.all ,甚至在使用迭代的结果.each

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

尝试这个:

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

暂无
暂无

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

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