我的数据模型:
Rails模型:
class User < ApplicationRecord
end
class Collection < ApplicationRecord
has_many :arts
belongs_to :user
end
class Art < ApplicationRecord
belongs_to :collection
end问题代码:
def index
@arts = Art.where(:user => current_user)
end错误消息:
SQLite3::SQLException: no such column: arts.user: SELECT "arts".* FROM "arts" WHERE "arts"."user" = 1我已经将art_id和user_id作为索引添加到Collection表并运行rake db:migrate。
我也试过
has_many :arts, :through => :collections 在用户模型中仍然得到了错误。
发布于 2017-02-18 15:49:22
Art和User之间没有直接联系,所以您不能简单地通过不存在的字段user来查询艺术。
如果要查找属于给定用户的所有art,则需要通过collections表进行连接,这是将用户绑定到art的唯一方法:
Art.joins(:collection => :user).where(users: { id: current_user.id })发布于 2017-02-18 19:29:52
如果你有
has_many :arts, :through => :collections在您的用户模型中使用
current_user.arts
为了获得一个用户的所有艺术。
如果仍有错误,请使用以下查询
Art.joins(:collection).where('collections.user_id = ?',current_user.id)
这应该能胜任这份工作。
发布于 2017-02-18 15:38:37
用于查询
@arts = Art.where(:user => current_user)你需要艺术方面的user_id。
也就是说,你需要
class Art < ApplicationRecord
belongs_to :collection
belongs_to :user
endhttps://stackoverflow.com/questions/42316777
复制相似问题