Rails:为用户设置最喜欢的食谱,但不断出现相同的错误

时间:2016-05-25 07:56:06

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

作为用户,我希望能够将食谱添加到我的收藏夹中。不幸的是,当我尝试将食谱添加到我的收藏夹时,我得到以下error: Recipe(#69883866963220) expected, got NilClass(#46922250887180)

我按照'tutorial'作为指导原则

不知何故,它无法将其添加到用户的收藏夹中。当我使用Rails C并输入User.find(1).favorites时,它会返回一个空数组。

谁能帮我解决问题?提前谢谢!

我的模特:

class FavoriteRecipe < ActiveRecord::Base
  belongs_to :recipe
  belongs_to :user
end
class User < ActiveRecord::Base
  has_many :recipes

  # Favorite recipes of user
  has_many :favorite_recipes # just the 'relationships'
  has_many :favorites, through: :favorite_recipes, source: :recipe # the actual recipes a user favorites
end

class Recipe < ActiveRecord::Base
  belongs_to :user

  # Favorited by users
  has_many :favorite_recipes # just the 'relationships'
  has_many :favorited_by, through: :favorite_recipes, source: :user # the actual users favoriting a recipe
end

我的recipecontroller.rb:

def show
    @review = Review.new
    @recipe = Recipe.find(params[:id])
    @user = User.find(@recipe.user_id)
    @full_name = @recipe.user.first_name + " " + @recipe.user.last_name
    # @reviews = @recipe.reviews.page(params[:page]).order('created_at DESC')
  end

  # Add and remove favorite recipes
  # for current_user
  def favorite
    type = params[:type]
    if type == "favorite"
      current_user.favorites << @recipe
      redirect_to :back, notice: 'You favorited #{@recipe.name}'

    elsif type == "unfavorite"
      current_user.favorites.delete(@recipe)
      redirect_to :back, notice: 'Unfavorited #{@recipe.name}'

    else
      # Type missing, nothing happens
      redirect_to :back, notice: 'Nothing happened.'
    end
  end

路线:

resources :recipes, only: [:index, :show] do
    put :favorite, on: :member
end

我的观点:app / views / recipes / show.html.erb

  <% if current_user.favorites.exists?(id: @recipe.id) %>
    <%= link_to favorite_recipe_path(@recipe, type: "unfavorite"), method: :put do %>
      <ul class="list-inline product-controls">
        <li><i class="fa fa-heart"></i></li>
      </ul>
    <% end %>
  <% else %>
    <%= link_to favorite_recipe_path(@recipe, type: "favorite"), method: :put do %>
      <ul class="list-inline product-controls">
        <li><i class="fa fa-heart"></i></li>
      </ul>
    <% end %>
 <% end %>

1 个答案:

答案 0 :(得分:3)

根据您的关系,您需要将配方对象分配给用户。因此需要首先找到该对象,然后将其分配给用户。

def favorite
    @recipe = Recipe.find(params[:id])
    type = params[:type]
    if type == "favorite"
      current_user.favorites << @recipe
      redirect_to :back, notice: 'You favorited #{@recipe.name}'

    elsif type == "unfavorite"
      current_user.favorites.delete(@recipe)
      redirect_to :back, notice: 'Unfavorited #{@recipe.name}'

    else
      # Type missing, nothing happens
      redirect_to :back, notice: 'Nothing happened.'
    end
end