我在rails 3 app中使用了carrierwave gem来上传个人资料图片。在用户的主页上有一个链接可以更改他们的个人资料图片。要获取配置文件图片记录的ID,我在userhome控制器中有以下内容:
@profile_picture = ProfilePicture.find("user_id = ?", current_user.id)
# if no profile picture record, create one
if @profile_picture.empty?
ProfilePicture.create(:picture => "", :user_id => current_user.id )
end
我收到以下错误:
Couldn't find all ProfilePictures with IDs (user_id = ?, 1) (found 1 results, but was looking for 2)
以前没有看到此错误,网络搜索没有产生任何有用的信息。
感谢。
答案 0 :(得分:3)
您可以用一行完成所有这些(并修复错误):
@profile_picture = ProfilePicture.find_or_create_by_user_id(:user_id => current_user.id, :picture => "")
答案 1 :(得分:2)
find
方法采用id列表,而不是SQL代码段。你传递了两个参数,并假设它们都是ids。它一无所获。相反,我认为你想要这个:
@profile_picture = ProfilePicture.find_by_user_id(current_user.id)
答案 2 :(得分:0)
我是非常新的RoR,但我想知道您是否可以使用ProfilePicture.find_by_owner(owner_id)
或
ProfilePicture.find_by_sql("SELECT * FROM ProfilePicture WHERE owner.id = current_user.id")
Dunno,只花了我的两分钱(并尝试学习Ruby on Rails)
- 编辑 -
顺便说一句,我认为this post可能有用。