我在 Rails 中设置了 2 个模型:
class Category < ActiveRecord::Base
attr_accessible :name
has_many :platforms
end
和
class Platform < ActiveRecord::Base
attr_accessible :name, :url, :country
validates :name, :presence => true, :length => { :minimum => 5 }
validates :url, :presence => true, :length => { :minimum => 5 }
belongs_to :categories
end
这是我的平台控制器:
class PlatformsController < ApplicationController
# GET /platforms
# GET /platforms.json
def index
@platforms = Platform.all
@categories = Category.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @platforms }
end
end
# GET /platforms/1
# GET /platforms/1.json
def show
@platform = Platform.find(params[:id])
@categories = Platform.categories
respond_to do |format|
format.html # show.html.erb
format.json { render json: @platform }
end
end
# GET /platforms/new
# GET /platforms/new.json
def new
@platform = Platform.new
@categories = Category.all
respond_to do |format|
format.html # new.html.erb
format.json { render json: @platform }
end
end
# GET /platforms/1/edit
def edit
@platform = Platform.find(params[:id])
@categories = Category.find(:all)
end
# POST /platforms
# POST /platforms.json
def create
@platform = Platform.new(params[:platform])
#@categories = Category.new(params[:name])
@categories = @platform.categories.create(params[:categories])
respond_to do |format|
if @platform.save
format.html { redirect_to @platform, notice: 'Platform was successfully created.' }
format.json { render json: @platform, status: :created, location: @platform }
else
format.html { render action: "new" }
format.json { render json: @platform.errors, status: :unprocessable_entity }
end
end
end
# PUT /platforms/1
# PUT /platforms/1.json
def update
@platform = Platform.find(params[:id])
@categories = Category.find(:all)
respond_to do |format|
if @platform.update_attributes(params[:platform])
format.html { redirect_to @platform, notice: 'Platform was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @platform.errors, status: :unprocessable_entity }
end
end
end
# DELETE /platforms/1
# DELETE /platforms/1.json
def destroy
@platform = Platform.find(params[:id])
@platform.destroy
respond_to do |format|
format.html { redirect_to platforms_url }
format.json { head :no_content }
end
end
end
我不明白我做错了什么,但是当我尝试使用时,它没有正确地将类别分配给平台,也在平台索引视图中:
<%= platform.categories %>
它给了我错误找不到带有 id=“和这里的相应 id”的类别
我真的很困惑,因为我遵循了这个教程。
我使用 Rails 3.2.8