사용자가 Food2Fork API을 사용하여 래서 피를 검색하고 찾아 볼 수있게 해주는 레일스 애플리케이션을 연구 중입니다.레일에 사용자 즐겨 찾기 추가
버전 : 레일 5.0.0.1, 루비 2.3.1p112 (2016년 4월 26일 개정 54768) [64-mingw32]
나는 사용자 모델, 레시피 모델 및 즐겨 찾기 모델을 가지고있다. 내가 찾은 좋아하는 요리법에 로그인 한 사용자를 허용하려고합니다. 검색 및 탐색 기능은 사용자와의 로그인/로그 아웃뿐만 아니라 요리법과 함께 작동하므로 사용자 나 API에 문제가없는 것으로 알고 있습니다.
undefined method `relation_delegate_class' for Recipe:Class
사용자 모델 :
class User < ApplicationRecord
has_secure_password
has_many :favorites
has_many :favorite_recipes, through: :favorites, source: :favorited, source_type: 'Recipe'
end
레시피 모델을 내가 (코드 하단에)보기를 열 때
이 대한 즐겨 찾기 시스템을 구현하려고, 나는 다음과 같은 오류를 얻고있다 :
require 'httparty'
class Recipe
include HTTParty
#define API base URL and key for project
ENV['FOOD2FORK_API_KEY'] = 'api_key_here' # (this was edited so I don't make my key public)
base_uri 'http://food2fork.com/api'
default_params key: ENV['FOOD2FORK_API_KEY']
format :json
#search method
def self.for term
get('/search', query: { q: term }) ["recipes"]
end
#show method
def self.find term
get('/get', query: { rId: term }) ["recipe"]
end
def self.browse term
get('/browse', query: { q: term }) ["recipes"]#random number
end
end
좋아하는 모델 :
class Favorite < ApplicationRecord
belongs_to :user
belongs_to :favorited, polymorphic: true
end
사용자 컨트롤러 :
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
session[:user_id] = @user.id
redirect_to '/home'
else
redirect_to '/register'
end
end
private
def user_params
params.require(:user).permit(:username, :email, :password, :location, :fname, :lname)
end
end
레시피 컨트롤러 :
class RecipesController < ApplicationController
def search
@search_term = params[:ingredient]
@recipes = Recipe.for(@search_term)
end
def show
@id_r = params[:id]
@recipe = Recipe.find(@id_r)
end
def browse
@rand_num = params[:random]
@rand_recipes = Recipe.for(@rand_num)
end
end
좋아하는 컨트롤러 :
class FavoriteRecipesController < ApplicationController
before_action :set_recipe
def create
if Favorite.create(favorited: @recipe, user: current_user)
redirect_to @recipe, notice: 'Recipe favorited'
else
redirect_to @recipe, alert: 'Something went wrong.'
end
end
def destroy
Favorite.where(favorited_id: @recipe.rId, user_id: current_user.id).first.destroy
redirect_to @recipe, notice: 'Recipe unfavorited.'
end
private
def set_recipe
@recipe = Recipe.find(params[:recipe_id] || params[:id])
end
end
데이터베이스 스키마
ActiveRecord::Schema.define(version: 20161123033852) do
create_table "favorite_recipes", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
t.integer "recipe_id"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "favorites", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
t.integer "user_id"
t.string "favorited_type"
t.integer "favorited_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["favorited_type", "favorited_id"], name: "index_favorites_on_favorited_type_and_favorited_id", using: :btree
t.index ["user_id"], name: "index_favorites_on_user_id", using: :btree
end
create_table "users", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
t.string "username"
t.string "email"
t.string "password_digest"
t.decimal "location", precision: 10
t.string "fname"
t.string "lname"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_foreign_key "favorites", "users"
end
그리고 마지막으로,보기, 요리법/show.html :
<% this_recipe = @recipe %>
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
</div>
<div class="container-fluid bg-grey" style="text-align:center">
<h1><%= this_recipe["title"] %></strong></h1>
<% if (this_recipe.nil? or this_recipe == []) %>
<p> <h2><strong>Sorry</b>, that recipe doesn't exist.</h2></p>
<% else %>
<center><div class="recipebox" style="padding:20px;margin:10px; border:1px solid orange; background:white;width:75%">
<div class="row">
<div class="col-md-6">
<p><%= link_to(image_tag(this_recipe["image_url"], height: '400', width: '400'), this_recipe["source_url"])%><br/>
(<%= link_to("View Recipe Source", this_recipe["source_url"]) %>)</p>
</div>
<div class="col-md-6">
<h2>Ingredients:</h2>
<% ingredients = this_recipe["ingredients"] %>
<% ingredients.each do |i| %>
• <%= i %> <br/>
<% end %>
<p>
<%- unless current_user.favorite_recipes.exists?(id: @recipe.rId) -%>
<%= link_to 'Add to favorites', favorite_recipes_path(recipe_id: @project), method: :post %>
<%- else -%>
<%= link_to 'Remove from favorites', favorite_recipe_path(@recipe), method: :delete %>
<%- end -%>
</div>
<% end %>
</center>
</div>
</div>
</div>
내가 제대로 모델을 연결하고 있지 않다 만약 내가 확실하지 오전, 나는 정확하게 정보를 전달하고 있지 않다, 또는 정확히 원인을 오류. 이 문제를 해결해 주셔서 감사합니다.
편집
추적 :
activerecord (5.0.0.1) lib/active_record/relation/delegation.rb:106:in `relation_class_for'
activerecord (5.0.0.1) lib/active_record/relation/delegation.rb:100:in `create'
activerecord (5.0.0.1) lib/active_record/associations/collection_association.rb:47:in `reader'
activerecord (5.0.0.1) lib/active_record/associations/builder/association.rb:111:in `favorite_recipes'
app/views/recipes/show.html.erb:32:in `_app_views_recipes_show_html_erb___356804060_113751160'
actionview (5.0.0.1) lib/action_view/template.rb:158:in `block in render'
activesupport (5.0.0.1) lib/active_support/notifications.rb:166:in `instrument'
actionview (5.0.0.1) lib/action_view/template.rb:348:in `instrument'
actionview (5.0.0.1) lib/action_view/template.rb:156:in `render'
actionview (5.0.0.1) lib/action_view/renderer/template_renderer.rb:54:in `block (2 levels) in render_template'
actionview (5.0.0.1) lib/action_view/renderer/abstract_renderer.rb:42:in `block in instrument'
activesupport (5.0.0.1) lib/active_support/notifications.rb:164:in `block in instrument'
activesupport (5.0.0.1) lib/active_support/notifications/instrumenter.rb:21:in `instrument'
activesupport (5.0.0.1) lib/active_support/notifications.rb:164:in `instrument'
actionview (5.0.0.1) lib/action_view/renderer/abstract_renderer.rb:41:in `instrument'
actionview (5.0.0.1) lib/action_view/renderer/template_renderer.rb:53:in `block in render_template'
actionview (5.0.0.1) lib/action_view/renderer/template_renderer.rb:61:in `render_with_layout'
로그 :
기본적인 사용을 위해ActionView::Template::Error (undefined method `relation_delegate_class' for Recipe:Class):
29: <% end %>
30:
31: <p>
32: <%- unless current_user.favorite_recipes.exists?(id: @recipe.rId) -%>
33: <%= link_to 'Add to favorites', favorite_recipes_path(recipe_id: @recipe), method: :post %>
34: <%- else -%>
35: <%= link_to 'Remove from favorites', favorite_recipe_path(@recipe), method: :delete %>
app/views/recipes/show.html.erb:32:in `_app_views_recipes_show_html_erb___356804060_113751160'
Rendering C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb within rescues/layout
Rendering C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb
Rendered C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (6.0ms)
Rendering C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb
Rendered C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.9ms)
Rendering C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
Rendered C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (2.0ms)
Rendered C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb within rescues/layout (1241.0ms)
오류에 대한 스택 추적을 표시 할 수 있습니까? –
로그와 로그가 추가되어 도움이 될 수 있습니다. @maxpleaner – crackedact0r
Recipe 클래스가 실제로 ApplicationRecord 모델 인 것처럼 보이지 않습니다. 어쩌면 HTTParty 항목을 별도의 클래스로 추출 할 수 있습니다. 그 외에는 확실하지 않습니다. –