2 가지 모델, 스포츠 모델 및 팀 모델이 있습니다. 팀 모델 belongs_to : 스포츠 및 스포츠 모델 has_many : 팀.레일즈 관련 모델 ID 생성시
스포츠 모델 :
class Sport < ActiveRecord::Base
has_many :teams
has_many :competitions
has_many :games
end
팀 모델 : 새로운 팀을 만들 때
class Team < ActiveRecord::Base
belongs_to :sport
has_many :competition_teams
has_many :competitions, :through => :competition_teams
has_many :home_games, :foreign_key => "home_team_id", :class_name => "Game"
has_many :visiting_games, :foreign_key => "visiting_team_id", :class_name => "Game"
end
은 항상 스포츠에 연결해야합니다. 예를 들어, 하키의 ID가 1 인 경우, 하키에서 생성 된 팀은 스포츠 ID를 포함해야합니다.
class TeamsController < ApplicationController
before_action :set_team, only: [:show, :edit, :update, :destroy]
# GET /games
# GET /games.json
def index
@teams = Team.all
end
# GET /games/1
# GET /games/1.json
def show
end
# GET /games/new
def new
@team = Team.new
end
# GET /games/1/edit
def edit
end
# POST /games
# POST /games.json
def create
@team = Team.new(team_params)
respond_to do |format|
if @team.save
format.html { redirect_to @team, notice: 'team was successfully created.' }
format.json { render action: 'show', status: :created, location: @team }
else
format.html { render action: 'new' }
format.json { render json: @team.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /games/1
# PATCH/PUT /games/1.json
def update
respond_to do |format|
if @team.update(team_params)
format.html { redirect_to @team, notice: 'team was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @team.errors, status: :unprocessable_entity }
end
end
end
# DELETE /games/1
# DELETE /games/1.json
def destroy
@team.destroy
respond_to do |format|
format.html { redirect_to sports_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_team
@team = Team.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def team_params
params[:team].permit(:name, :sport_id)
end
end
나는 경로에서 다음을 수행하려고 :하려고 할 때 오류를
resources :sports do
resources :teams
end
을하지만, 얻을
create_table "sports", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "teams", force: true do |t|
t.string "name"
t.integer "sport_id"
t.datetime "created_at"
t.datetime "updated_at"
end
이 팀의 컨트롤러 : 아래는 현재의 스키마입니다 다음 URL에서 팀을 만드십시오./sports/1/teams/new
오류는 다음과 같습니다. undefined metho # < 번호 D 'teams_path'0x007fafb4b9b0c0>
응용 프로그램이/뷰/팀이/_form.html.erb 1 호선 제기:
TeamsController의 새 작업에서 id 대신 sport_id를 사용하십시오. – vee
레일 콘솔을 체크인하면 스포츠 ID가 추가되지 않습니다. – Dileet
sport_id가 nil을 말하고 있습니다. – Dileet