我是Ruby on Rails的新手,我开始使用脚手架并手动添加另一个模型。我似乎无法从我手动生成的模型中获取值以在我的索引视图中显示。
我的第一个模型是高尔夫球场名称,城市,标准杆和洞穴。第二个模型是每个球场的洞数。出于某种原因,我无法获得显示的孔数以下是我的代码。 模型
class Course < ActiveRecord::Base
has_many :holes
end
class Hole < ActiveRecord::Base
belongs_to :course
end
控制器
class CoursesController < ApplicationController
before_action :set_course, only: [:show, :edit, :update, :destroy]
# GET /courses
# GET /courses.json
def index
@courses = Course.all
@holes = Hole.all
end
# GET /courses/1
# GET /courses/1.json
def show
end
# GET /courses/new
def new
@course = Course.new
end
# GET /courses/1/edit
def edit
end
# POST /courses
# POST /courses.json
def create
@course = Course.new(course_params)
respond_to do |format|
if @course.save
format.html { redirect_to @course, notice: 'Course was successfully created.' }
format.json { render :show, status: :created, location: @course }
else
format.html { render :new }
format.json { render json: @course.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /courses/1
# PATCH/PUT /courses/1.json
def update
respond_to do |format|
if @course.update(course_params)
format.html { redirect_to @course, notice: 'Course was successfully updated.' }
format.json { render :show, status: :ok, location: @course }
else
format.html { render :edit }
format.json { render json: @course.errors, status: :unprocessable_entity }
end
end
end
# DELETE /courses/1
# DELETE /courses/1.json
def destroy
@course.destroy
respond_to do |format|
format.html { redirect_to courses_url, notice: 'Course was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_course
@course = Course.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def course_params
params.require(:course).permit(:name, :city, :hole_id)
end
end
查看
<p id="notice"><%= notice %></p>
<p>
<strong>Name:</strong>
<%= @course.name %>
</p>
<p>
<strong>City:</strong>
<%= @course.city %>
</p>
<p>
<strong>Hole:</strong>
<%= @course.holes %>
</p>
<%= link_to 'Edit', edit_course_path(@course) %> |
<%= link_to 'Back', courses_path %>
答案 0 :(得分:0)
<%= @course.holes %>
为您提供ActiveRecord_Associations_CollectionProxy
您需要提出 size , length 或 count 才能获取属于@course
的洞总数,这意味着您必须说@course.holes.size
,@course.holes.length
或@course.holes.count
。请查看文档以了解这三者之间的差异。