【发布时间】:2012-06-10 09:18:59
【问题描述】:
有没有更简单的方法可以从表中返回关系行以访问存储在那里的数据?
我有两个使用 has_many :through 相关的模型,第三个模型设置为中间。我的模型由 User、Recipe 和 RecipeInfo 组成。
现在,为了访问为特定用户的食谱信息存储的数据,我正在使用与此类似的 Rails 查询
info = @user.recipeInfos.where("recipe_id=#{@recipe.id}")
我想知道是否有比使用 .where() 方法更简单的方法来访问用户食谱信息的这一行。
编辑:
recipe = Recipe.find(params[:id])
user = current_user
current_user 在用户登录时由sessions[:user_id] = current_user 定义。
【问题讨论】:
-
只是为了一点代码上下文,您如何确定要查找的配方(@recipe 是如何确定的)?
-
我已经根据上下文编辑了我的问题。
-
你为什么不想使用
where?@user.recipeInfos.where(:recipe_id => @recipe.id).first会自动将其限制为单个结果,如果这是您所担心的。不相关,为什么recipeInfos的大写异常?
标签: mysql ruby-on-rails ruby-on-rails-3 has-many-through