簡體   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