我有一个ruby表单,可以在我的应用上提交练习报告。练习has_many
报告。我想创建一个if语句,只有在该练习的最后一个报告保存超过3小时之前才会显示此表单。
到目前为止,我有:
但这是在创建一个NoMethodError
undefined method 'report' for #<Exercise:0x007f9c892f48b0>
。
它显示在我的workouts#show
页面上(锻炼has_many
练习,万一有帮助),所以我相信这是卫冕的控制者:
class WorkoutsController < ApplicationController
def index
@workouts = Workout.all
end
def show
@workout = Workout.find(params[:id])
@exercise = Exercise.new
@report = Report.new
end
def new
@workout = Workout.new
@workout.user_id = current_user
end
def create
@workout = Workout.new(workout_params)
@workout.user = current_user
if @workout.save
flash[:notice] = "Workout was saved successfully."
redirect_to @workout
else
flash.now[:alert] = "Error creating workout. Please try again."
render :new
end
end
def edit
@workout = Workout.find(params[:id])
end
def update
@workout = Workout.find(params[:id])
@workout.name = params[:workout][:name]
@workout.workout_type = params[:workout][:workout_type]
@workout.teaser = params[:workout][:teaser]
@workout.description = params[:workout][:description]
@workout.video = params[:workout][:video]
@workout.difficulty = params[:workout][:difficulty]
@workout.trainer = params[:workout][:trainer]
@workout.user_id = params[:workout][:user_id]
if @workout.save
flash[:notice] = "Workout was updated successfully."
redirect_to @workout
else
flash.now[:alert] = "Error saving workout. Please try again."
render :edit
end
end
def destroy
@workout = Workout.find(params[:id])
if @workout.destroy
flash[:notice] = "\"#{@workout.name}\" was deleted successfully."
redirect_to action: :index
else
flash.now[:alert] = "There was an error deleting the workout."
render :show
end
end
private
def workout_params
params.require(:workout).permit(:name, :workout_type, :teaser, :description, :video, :difficulty, :trainer, :user_id)
end
end
我出错的任何想法?
其他信息:
此位在技术上位于我的workouts#show
页面上:
<% if @workout.exercises.count == 0 %>
<p>Looks like you get a freebie for this one! No score report today. Rest up and drink some water. It ain't always that easy...</p>
<% else %>
<% @workout.exercises.each do |exercise| %>
<%= render 'reports/form', report: @report, exercise: exercise %>
<% if current_user.admin? %>
<div class="text-center"><%= link_to "Delete #{exercise.name}", [exercise], method: :delete, data: { confirm: 'Are you sure?' } %></div>
<% end %>
<hr>
<% end %>
但是这里是它呈现的部分,其中有问题的代码实际上在于:
<% if exercise.report.last != nil && exercise.report.last.created_at < ( DateTime.now - (3/24.0)) %>
<%= form_for report,
:url => { :controller => "reports",
:action => :create,
:exercise_id => exercise.id } do |f| %>
<div class="row">
...
答案 0 :(得分:0)
您似乎在调用单一report
而不是reports
。
if exercise.report.last
如果报告与has_many
的锻炼有关,则需要使用exercise.reports.last
此外,您在提问时提到了results
,但在视图中调用reports
。
练习有很多结果。
...
exercise.report.last
请务必使用适当的复数方法reports
或results