2016-07-30 6 views
0

Я новичок в рельсах, поэтому я все еще пытаюсь понять, так что любая помощь очень ценится! Я создаю приложение, которое будет определять «сезоны», и с этими сезонами будет много «танцевальных классов». После создания сезона, вы должны иметь возможность создавать «danceclasses», так как часть моего шоу на сезонах у меня есть:Связанные модели в рубине на рельсах

<h2>Dance Classes Created</h2> 
<%= @seasons.danceclass.each do |danceclass| %> 
<p> 

Однако я получаю следующее сообщение об ошибке:

undefined method `danceclass' for nil:NilClass 

Моих модель данных: у меня есть таблица сезонов, таблица danceclasses и таблица season_danceclasses.

Моя модель для сезонов это:

class Season < ActiveRecord::Base 
    has_many :season_class 
    has_many :danceclass, through: :season_class 
end 

Моя модель для танцевальных классов выглядит следующим образом:

class Danceclass < ActiveRecord::Base 
    belongs_to :season 
    has_many :student_class 
    has_many :student, through: :student_class 
end 

И моя модель season_danceclass выглядит следующим образом:

class SeasonDanceclasses < ActiveRecord::Base 
    belongs_to :season 
    belongs_to :danceclass 
end 

Мой контроллер_по_контроля выглядит так:

class SeasonsController < ApplicationController 
    before_action :set_season, only: [:show, :edit, :update, :destroy] 

    # GET /seasons 
    # GET /seasons.json 
    def index 
    @seasons = Season.all 
    end 

    # GET /seasons/1 
    # GET /seasons/1.json 
    def show 
    end 

    # GET /seasons/new 
    def new 
    @season = Season.new 
    end 

    # GET /seasons/1/edit 
    def edit 
    end 

    # POST /seasons 
    # POST /seasons.json 
    def create 
    @season = Season.new(season_params) 

    respond_to do |format| 
     if @season.save 
     format.html { redirect_to @season, notice: 'Season was successfully created.' } 
     format.json { render :show, status: :created, location: @season } 
     else 
     format.html { render :new } 
     format.json { render json: @season.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # PATCH/PUT /seasons/1 
    # PATCH/PUT /seasons/1.json 
    def update 
    respond_to do |format| 
     if @season.update(season_params) 
     format.html { redirect_to @season, notice: 'Season was successfully updated.' } 
     format.json { render :show, status: :ok, location: @season } 
     else 
     format.html { render :edit } 
     format.json { render json: @season.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # DELETE /seasons/1 
    # DELETE /seasons/1.json 
    def destroy 
    @season.destroy 
    respond_to do |format| 
     format.html { redirect_to seasons_url, notice: 'Season was successfully destroyed.' } 
     format.json { head :no_content } 
    end 
    end 

    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_season 
     @season = Season.find(params[:id]) 
    end 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def season_params 
     params.require(:season).permit(:season_name, :season_start, :season_end) 
    end 
end 

Что я делаю неправильно?

EDIT: Добавление schema.rb

# encoding: UTF-8 
# This file is auto-generated from the current state of the database. Instead 
# of editing this file, please use the migrations feature of Active Record to 
# incrementally modify your database, and then regenerate this schema definition. 
# 
# Note that this schema.rb definition is the authoritative source for your 
# database schema. If you need to create the application database on another 
# system, you should be using db:schema:load, not running all the migrations 
# from scratch. The latter is a flawed and unsustainable approach (the more migrations 
# you'll amass, the slower it'll run and the greater likelihood for issues). 
# 
# It's strongly recommended that you check this file into your version control system. 

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

    create_table "danceclasses", force: :cascade do |t| 
    t.string "class_id",   limit: 255 
    t.string "class_name",  limit: 255 
    t.text  "class_description", limit: 65535 
    t.integer "min_students",  limit: 4 
    t.integer "max_students",  limit: 4 
    t.string "category",   limit: 255 
    t.datetime "start_date" 
    t.datetime "end_date" 
    t.integer "week_frequency", limit: 4 
    t.integer "day_frequency",  limit: 4 
    t.string "start_time",  limit: 255 
    t.string "end_time",   limit: 255 
    t.integer "fee",    limit: 4 
    t.string "level",    limit: 255 
    t.datetime "created_at",      null: false 
    t.datetime "updated_at",      null: false 
    end 

    create_table "season_classes", force: :cascade do |t| 
    t.integer "season_id",  limit: 4 
    t.integer "danceclass_id", limit: 4 
    end 

    create_table "seasons", force: :cascade do |t| 
    t.string "season_name", limit: 255 
    t.datetime "season_start" 
    t.datetime "season_end" 
    t.datetime "created_at",    null: false 
    t.datetime "updated_at",    null: false 
    end 

    create_table "student_classes", force: :cascade do |t| 
    t.integer "student_id", limit: 4 
    t.integer "class_id", limit: 4 
    end 

    create_table "students", force: :cascade do |t| 
    t.string "first_name", limit: 255 
    t.string "last_name",  limit: 255 
    t.string "student_id", limit: 255 
    t.datetime "date_of_birth" 
    t.text  "notes",   limit: 65535 
    t.string "gender",  limit: 255 
    t.datetime "created_at",     null: false 
    t.datetime "updated_at",     null: false 
    end 

    create_table "user_students", force: :cascade do |t| 
    t.integer "user_id", limit: 4 
    t.integer "student_id", limit: 4 
    end 

    create_table "users", force: :cascade do |t| 
    t.string "username",  limit: 255 
    t.string "email",   limit: 255 
    t.string "password",  limit: 255 
    t.string "first_name", limit: 255 
    t.string "last_name",  limit: 255 
    t.string "phone_number", limit: 255 
    t.datetime "date_of_birth" 
    t.string "street_1",  limit: 255 
    t.string "street_2",  limit: 255 
    t.string "city",   limit: 255 
    t.string "state",   limit: 255 
    t.string "zipcode",  limit: 255 
    t.boolean "enabled" 
    t.boolean "is_admin" 
    t.datetime "created_at",    null: false 
    t.datetime "updated_at",    null: false 
    end 

end 
+0

Не могли бы вы поделиться своим schema.rb? Кстати, вы должны использовать множественное имя при объявлении ассоциации has_many. – utkuDAT

+0

добавлен schema.rb – Blogger11

+0

У него возникла ошибка .. потому что @seasons содержат более 1 записи .. так что вы можете получить только несколько танцевальных классов 1 сезона ... это будет во внутреннем цикле. – Vishal

ответ

0

Вы должны изменить has_many ассоциации должным образом.

class Season < ActiveRecord::Base 
    has_many :season_classes 
    has_many :danceclasses, through: :season_class 
end 

Надеюсь, это поможет вам!

0

Прежде всего ассоциаций, которые заняли должна быть во множественном числе для has_many,

class Season < ActiveRecord::Base 
    has_many :season_classes 
    has_many :dance_classes, through: :season_classes 
end 


class Danceclass < ActiveRecord::Base 
    belongs_to :season 
    has_many :student_classes 
    has_many :students, through: :student_classes 
end 

class SeasonDanceclasses < ActiveRecord::Base 
    belongs_to :season 
    belongs_to :danceclass 
end 

Теперь, когда вы сказали, что мнение показать страницу для сезона вашего сезона шоу действия является,

class SeasonsController < ApplicationController 
    before_action :set_season, only: [:show, :edit, :update, :destroy] 

    def index 
    @seasons = Season.all 
    end 

    def show 
    end 

end 

Ваш метод показа содержит @season переменный, но не @seasons, который был установлен в set_season action,

so app/views/seasons/show.html.erb is,

Это с вашей старой ассоциации

<h2>Dance Classes Created</h2> 
<% @season.danceclass.each do |danceclass| %> 
----------- 
---------- 
<% end %> 
<p></p> 

Это с измененными ассоциациями

<h2>Dance Classes Created</h2> 
<% @season.dance_classes.each do |danceclass| %> 
----------- 
---------- 
<% end %> 
<p></p> 
Смежные вопросы