Rails:选择返回nil的位置

时间:2014-08-27 18:47:56

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

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

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

但是store_id总是为零。我不确定我做错了什么。

1 个答案:

答案 0 :(得分: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