【问题标题】:Select single row from relation table in Rails从 Rails 的关系表中选择单行
【发布时间】: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


【解决方案1】:

您可以将这四行代码缩短为

info = current_user.recipeInfos.find_by_id(params[:id])

.

【讨论】:

  • 太棒了。这正是我一直在寻找的。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-26
  • 2023-03-22
相关资源
最近更新 更多