2015-07-27 3 views
-2

Я пытаюсь добавить категории к каждому рецепту. Пользователь выбирает категорию через форму. Я получаю неинициализированную постоянную ошибку Recipe :: CategoryId, знает ли кто-нибудь что?uninitialized constant Рецепт :: CategoryId

рецепт модель:

class Recipe < ActiveRecord::Base 
    validates :description, :nickname, :title, :ingredients, :instructions, :category_ids, presence: true 

    has_many :category_ids 
end 

Категория Модель:

class Category < ActiveRecord::Base 
    belongs_to :recipes 
end 

рецепты контроллера:

class RecipesController < ApplicationController 
    def index 
    @recipes = Recipe.all 
    end 

    def show 
    @recipe = Recipe.find(params[:id]) 
    end 

    def new 
    @recipe = Recipe.new 

    end 

    def edit 
    @recipe = Recipe.find(params[:id]) 
    end 

    def create 
    @recipe = Recipe.new(recipe_params) 

    if @recipe.save 
     redirect_to recipes_url 
    else 
     render:new 
    end 
end 

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

    if @recipe.update_attributes(recipe_params) 
     redirect_to recipe_path(@recipe) 
    else 
     render :edit 
    end 
    end 

    def destroy 
    @recipe = Recipe.find(params[:id]) 
    @recipe.destroy 
    redirect_to recipes_path 
    end 

    private 
    def recipe_params 
    params.require(:recipe).permit(:nickname, :website, :instagram, :title, :description, :instructions, :ingredients, :notes, :embed, :photo, :category_ids) 
    end 

end 

Форма:

<%= form_for(@recipe) do |f| %> 

<% if @recipe.errors.any? %> 
    <div id="error_explanation"> 
     <h2><%= pluralize(@recipe.errors.count, "error") %> prohibited this recipe from being saved:</h2> 

     <ul> 
     <% @recipe.errors.full_messages.each do |msg| %> 
     <li><%= msg %></li> 
     <% end %> 
     </ul> 
    </div> 
    <% end %> 


    <div class="field"> 
    <%= f.label :nickname %><br /> 
    <%= f.text_field :nickname %> 
    </div> 
    <div class="field"> 
    <%= f.label :website %><br /> 
    <%= f.text_area :website %> 
    </div> 
    <div class="field"> 
    <%= f.label :instagram %><br /> 
    <%= f.text_area :instagram %> 
    </div> 
    <div class="field"> 
    <%= f.label :title %><br /> 
    <%= f.text_area :title %> 
    </div> 
    <div class="field"> 
    <%= f.label :description %><br /> 
    <%= f.text_area :description %> 
    </div> 
    <div class="field"> 
    <%= f.label :ingredients %><br /> 
    <%= f.text_area :ingredients %> 
    </div> 
    <div class="field"> 
    <%= f.label :instructions %><br /> 
    <%= f.text_area :instructions %> 
    </div> 
    <div class="field"> 
    <%= f.label :notes %><br /> 
    <%= f.text_area :notes %> 
    </div> 
    <div class="field"> 
    <%= f.label :embed %><br /> 
    <%= f.text_area :embed %> 
    </div> 
    <div class="field"> 
    <%= f.label :photo %><br /> 
    <%= f.text_area :photo %> 
    </div> 
    <div class="field"> 

<%= f.collection_check_boxes :category_ids, Category.all, :id, :name %> 

</div> 

    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 

рецепт миграции:

class CreateRecipes < ActiveRecord::Migration 
    def change 
    create_table :recipes do |t| 
    t.string :nickname 
    t.string :website 
    t.string :instagram 
    t.string :title 
    t.string :description 
    t.string :ingredients 
    t.string :instructions 
    t.string :notes 
    t.string :embed 
    t.string :photo 

     t.timestamps null: false 
    end 
    end 
end 

категории:

class CreateCategories < ActiveRecord::Migration 
def change 
    create_table :categories do |t| 
     t.string :name 
     t.timestamps 
    end 
    end 
end 

схема:

ActiveRecord::Schema.define(version: 20150722174136) do 

    create_table "categories", force: :cascade do |t| 
    t.string "name" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    end 



    create_table "recipes", force: :cascade do |t| 
    t.string "nickname" 
    t.string "website" 
    t.string "instagram" 
    t.string "title" 
    t.string "description" 
    t.string "ingredients" 
    t.string "instructions" 
    t.string "notes" 
    t.string "embed" 
    t.string "photo" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    end 

end 
+0

это 'has_many: category_ids' должен быть' has_many: проверка categories' также должны быть по категориям, а не category_ids – Athar

+0

А также 'BELONGS_TO : recipes' должен быть 'own_to: recipe'. – Pavan

+0

Спасибо, ребята! за исключением того, что я получаю эту ошибку: ошибка запретила сохранение этого рецепта: Категории не могут быть пустыми ... почему он говорит, что это пустое, если я выбрал его? – icecreamrabbit

ответ

1

Предполагая, что вы хотите отношения многие ко многим между рецептами и категориями, сначала создать многие ко многим соской таблицу соединений следующим образом:

create_table "categories_recipes" do |t| 
    t.integer "recipe_id" 
    t.integer "category_id" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
end 

Затем добавьте ассоциации.

class Recipe < ActiveRecord::Base 
    validates :description, :nickname, :title, :ingredients, :instructions, :category_ids, presence: true 

    has_and_belongs_to_many :categories 
end 

Вы должны добавить его к категории модели, а также

class Category < ActiveRecord::Base 
    #other stuffs 
    has_and_belongs_to_many :recipes 
end 
+0

спасибо! теперь я получаю эту ошибку: не удалось найти таблицу «categories_recipes» ... должен ли я создать таблицу? если да, то что я должен положить внутрь? – icecreamrabbit

+0

nvm получил это благодаря работе! – icecreamrabbit

Смежные вопросы