【发布时间】:2015-09-08 05:49:06
【问题描述】:
Rails 和一般编程的新手,所以这里可能缺少一些基本的东西。我正在制作一个带有 3 个模型的简单运动追踪器:运动(不同类型的运动表)、锻炼(该会话完成的运动表)、提升(两者之间的连接表,还包括重量、组数和次数每个练习完成)。
问题:在锻炼中添加超过 1 个练习后,显示视图上的表格会为每个练习呈现超过 1 个条目(屏幕截图:http://imgur.com/MMYEkNr)。一切都正确写入数据库。
问题:如何以正确的方式进行此渲染,我做错了什么?
这是锻炼控制器:
class WorkoutsController < ApplicationController
def index
@workouts = Workout.all
end
def new
@workout = Workout.new
@lift = Lift.new
end
def create
@workout = Workout.new(params[:workout])
@workout.save
@lift = Lift.new(params[:lift])
@lift.workout_id = @workout.id
@lift.save
redirect_to @workout
end
def show
@workout = Workout.find(params[:id])
end
def edit
@workout = Workout.find(params[:id])
end
def update
@workout = Workout.find(params[:id])
@lift = Lift.new(params[:lift])
@lift.workout_id = @workout.id
@lift.save
redirect_to @workout
end
end
这是显示视图
<h1> Workout Number <%= @workout.id %></h1>
<div class="container">
<table class="table table-striped">
<thead>
<th>Excercize</th>
<th>Sets</th>
<th>Reps</th>
<th>Weight</th>
</thead>
<tbody>
<% @workout.exercises.each do |w| %>
<% @workout.lifts.each do |e| %>
<tr>
<td><%= w.name %></td>
<td><%= e.sets %></td>
<td><%= e.reps %></td>
<td><%= e.weight %></td>
</tr>
</tbody>
<% end %>
<% end %>
</table>
</div>
<div class="btn btn-primary">
Add Exercise
<%= link_to 'Add Exercise', edit_workout_path %>
</div>
编辑添加锻炼模型:
class Workout < ActiveRecord::Base
attr_accessible :id, :title, :body
has_many :lifts
accepts_nested_attributes_for :lifts
has_many :exercises, through: :lifts
end
还有 Lifts 模型
class Lift < ActiveRecord::Base
attr_accessible :reps, :sets, :weight, :id,
:workout_id, :exercise_id, :exercise_name
belongs_to :exercise
belongs_to :workout
end
练习模型
class Exercise < ActiveRecord::Base
attr_accessible :name, :primary_area, :secondary_area,
:id
has_many :lifts
accepts_nested_attributes_for :lifts
has_many :workouts, through: :lifts
def name_for_select
name.capitalize
end
end
【问题讨论】:
-
请告诉我们您的
app/models/workout.rb -
刚刚添加到上面。谢谢
-
你能解释一下
Lift和Exercise模型之间的关系吗? -
锻炼和锻炼模型通过升降机有很多关系。锻炼模型列出了不同类型的锻炼(卧推、肩推等),Lift 模型还包括在特定锻炼期间完成了每个锻炼的多少(例如,2 组、10 公斤、5 次重复)。跨度>
-
如果我理解正确,这应该可以。如果不是,请给我错误,并附加另外两个模型的代码来提问。
标签: ruby-on-rails