0

Is there a simpler way of returning the relationship row from a table to access the data stored there?

I have two models related using has_many :through and the third model set up as the in-between. My models consist of a User, Recipe, and RecipeInfo.

Right now, in order to access the data stored for a particular user's recipe info, I'm using a Rails query similar to this

info = @user.recipeInfos.where("recipe_id=#{@recipe.id}")

I'm wondering if there is a simpler way of accessing this single row of a User's Recipe info rather than using the .where() method.

Edit:

recipe = Recipe.find(params[:id])

user = current_user

current_user is defined by sessions[:user_id] = current_user when the user logs in.

Christian Benincasa
  • 1,215
  • 1
  • 21
  • 45
  • Just for a bit of code context, how are you determining which recipe to look for (how is @recipe determined)? – cdesrosiers Jun 10 '12 at 00:48
  • I've edited my question with the context. – Christian Benincasa Jun 10 '12 at 01:15
  • Why don't you want to use `where`? `@user.recipeInfos.where(:recipe_id => @recipe.id).first` will automatically limit it to single result, if that's what you're worried about. Unrelated, why the unusual capitalization of `recipeInfos`? – x1a4 Jun 10 '12 at 01:19

1 Answers1

0

You can shorten those four lines of code to just

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

.

cdesrosiers
  • 8,862
  • 2
  • 28
  • 33