2012-04-19 37 views
1

我在Ruby on Rails中構建了一個小型的推文克隆。它有一個用戶模型,一個Micropost模型和一個關係模型。關係模型存儲隨後的用戶標識符和相應的以下用戶標識符。我試圖添加一個新按鈕,使當前用戶在其微博中跟隨所有其他用戶使用匹配參數。我已經將該參數添加到微型模型。問題是,當我查詢數據庫的模型微柱找到用戶返回Ruby on Rails SQL查詢返回#<ActiveRecord :: Relation:

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

這裏是我的人際關係控制器創建方法:

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 

非常感謝您提供的任何幫助。這是非常讚賞。

回答

1

首先Model.where的返回,你可以鏈上的其他經營者(另一.where.order等)

如果你想記錄

要在數據庫中的關係對象,你必須明確地關閉鏈.first.last,.all甚至迭代結果使用.each

秒 - 你爲什麼要嘗試直接插入結果到字符串使用#{matched_ids}?將調用#to_s關係對象上,而不是正確地建立這些對象的名單在查詢中使用

試試這個:

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