【问题标题】:Rails: Select where return nilRails:选择返回零的位置
【发布时间】:2014-08-27 18:47:56
【问题描述】:

我有一个 store 和一个 item 表。 在保存商品记录之前,我想获取属于当前用户的商店 ID。我试过这样做:

@item.store_id = Store.select("id").where(:user_id => current_user.id )

但 store_id 始终为零。我不确定我做错了什么。

【问题讨论】:

  • 尝试current_user.stores,如果你有适当的关联。在action 中添加断点并检查此查询的输出

标签: ruby-on-rails ruby-on-rails-4


【解决方案1】:

假设User属于store,Item属于store:

class User < ActiveRecord::Base
  belongs_to :store
end

class Item < ActiveRecord::Base
  belongs_to :store
end

然后您可以更直接地访问关联:

@item.store = current_user.store

【讨论】:

  • 为什么我需要向用户添加“belongs_to :store”?我目前拥有的是:商店中的“has_many :items belongs_to :user”。和“belongs_to :store belongs_to :user”到项目。
  • 那么一个用户可以拥有多个店铺?你如何确定用户的哪些商店应该与商品相关联?
猜你喜欢
  • 2017-09-07
  • 2015-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-20
相关资源
最近更新 更多