自从上一篇文章以来,我在Rails方面取得了重大进展。所以这就是目标!
rake执行时没有任何错误,因此第一个问题。如何检查对象是否实际创建?
耙文件:
require 'csv'
namespace :data do
desc "Imports data from course_listing.csv"
task :import_csv => :environment do
CSV.foreach("db/course_listing.csv") do |row|
Course.new(
:ID => row[0],
:type => row[1],
:location => row[2],
:meeting_days => row[3],
:start_time => row[4],
:stop_time => row[5],
)
end
end
end
接下来,这是我的控制器和型号。我需要做的就是打印属性,这样模型应该是准系统。
控制器:
class CoursesController < ApplicationController
def new
@courses = Course.new
end
def create
@course = Course.create(:ID, :type, :location, :meeting_days, :start_time, :stop_time)
end
def index
@courses = Course.all
end
end
型号:
class Course < ActiveRecord::Base
attr_accessor :ID, :type, :location, :meeting_days, :start_time, :stop_time
end
最后,这里是为#Course id抛出异常“未定义的方法`每个'的视图:nil,created_at:nil,updated_at:nil”
查看:
<table border="1" style="width:50%">
<tr>
<th>Type</th>
<th>Location</th>
<th>Meeting Days</th>
<th>Start Time</th>
<th>Stop Time</th>
</tr>
<% @courses.each do |course| %>
<tr>
<td><%= course.type %></td>
<td><%= course.location %></td>
<td><%= course.meeting_days %></td>
<td><%= course.start_time %></td>
<td><%= course.stop_time %></td>
</tr>
<% end %>
</table>
那我怎么能解决这个问题:)我是rails的新手,我仍然习惯了它!
谢谢!
答案 0 :(得分:0)
我只是回答你的第一个问题,你可以编辑将其他问题转移到他们自己的问题中。
通常,如果要检查数据库中是否正在创建/更新对象,快速方法是打开rails控制台(通过在终端中运行rails console
)并对其进行查询数据。有关您可以运行的查询的详细信息,请参阅the Active Record Query Interface docs。
测试rake任务的更好方法是使用测试库。这是intro to rspec和an example of specs for a rake task。
最后,为了节省您一点时间,该rake任务实际上不会将任何内容保存到数据库中。查看this answer to another question to see why。
答案 1 :(得分:0)
第一个答案。您可以通过设置validations来创建更严格且一致的模型。
在Rake任务期间,您可以使用隐式save!
检查进程,如果出现问题,它将在任何情况下都会抛出异常。
...
c = Course.new(...)
c.save!
...
第二个问题。
请找到关于nil/empty/false
here的详细说明。您可以使用trenary运算符检查字段。以下是如何更改代码的示例:
<td><%= course.stop_time.nil? ? 'N/A' : course.stop_time %></td>
它会把N / A&#39;如果数据丢失,则在表格单元格中。