gpt4 book ai didi

mysql - Ruby on Rails SQL 查询返回#
转载 作者:行者123 更新时间:2023-11-29 00:46:49 25 4
gpt4 key购买 nike

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

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

这里引用的是微博模型中的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

这是我的关系 Controller 创建方法:

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

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

遍历结果

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

试试这个:

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

关于mysql - Ruby on Rails SQL 查询返回#<ActiveRecord::Relation:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10229843/

25 4 0

Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com