kit*_*nky 1 sql activerecord ruby-on-rails active-record-query
我有一个Adventure模型,它是a Destination和a 之间的连接表User(并具有其他属性,如zipcode和time_limit).我想创建一个query将返回我所有的Destinations地方的Adventure那间Destination和User目前正试图创建一个Adventure不存在.
应用程序工作时的方式User点击开始一个新Adventure它会创建一个Adventure与user_id被认为User的id,然后运行方法来提供一个随机Destination,例如:
Adventure.create(user_id: current_user.id)(它实际上是在做current_user.adventures.new)但同样的事情
我尝试过从写作SQL queries到使用的一些东西.joins.这里有一些例子:
Destination.joins(:adventures).where.not('adventures.user_id != ?'), user.id)
Destination.joins('LEFT OUTER JOIN adventure ON destination.id = adventure.destination_id').where('adventure.user_id != ?', user.id)
以下内容应返回用户在任何冒险中尚未访问过的所有目的地:
destinations = Destination.where('id NOT IN (SELECT destination_id FROM adventures WHERE user_id = ?)', user.id)
Run Code Online (Sandbox Code Playgroud)
要选择随机的一个,请附加以下内容之一:
.all.sample
# or
.pluck(:id).sample
Run Code Online (Sandbox Code Playgroud)
取决于您是想要完整记录还是只是id.