我一直在教自己Ruby,我很难尝试将信息输出到文本文件中。文件已创建,没有抛出任何错误,但没有任何内容写入文件。我选择修改文件而不是写入文件,因为我不希望数据被覆盖。我知道这将是一个简单的答案,但我已经在墙上敲了一会儿。提前谢谢。
这是我的控制器
class EntriesController < InheritedResources::Base
actions :new, :show, :index, :edit, :update
before_filter :set_message, :only => [:update]
def save_to_file
playlist = 'playlist.txt'
File.open(playlist, 'a+') do |entry|
entry.each do |entry|
f.puts '#{entry.song} by #{entry.artist} on #{entry.album}'
end
end
end
def create
@entry = Entry.new(entry_params)
if @entry.save
flash[:notice] = "Your song was added"
save_to_file
redirect_to entries_path
else
flash[:error] = "Your song wasn't added. Please check all info and try agian."
render :new
end
end
private
def entry_params
params.require(:entry).permit(:artist, :album, :song)
end
def set_message
flash[:warning] = "Are you sure you want to overwrite this song information?"
end
end
答案 0 :(得分:2)
这里有4个错误:
count
def save_to_file
playlist = 'playlist.txt'
File.open(playlist, 'a+') do |entry| # 1
entry.each do |entry| # 2
f.puts '#{entry.song} by #{entry.artist} on #{entry.album}' # 3 and 4
end
end
end
是此处打开的|entry|
(File
)的实例,而不是playlist.txt
类的实例。语法是正确的(文件正确打开),但似乎有一些混乱(逻辑错误)。Entry
模型,您需要通过实例变量Entry
来实现,或者更好地将其作为参数传递给函数@entry
。由于save_to_file
指的是1个对象而不是集合,因此您不需要entry
。each
未定义,因此尝试调用任何方法都会导致错误。你可能想在这里使用第1页的变量。f
)在单引号中不起作用,您需要使用双引号。假设上述各点我将您的代码更改为以下内容:
"#{entry.song}"
并将def save_to_file(entry)
playlist = 'playlist.txt'
File.open(playlist, 'a+') do |f|
f.puts "#{entry.song} by #{entry.artist} on #{entry.album}"
end
end
方法称为EntriesController#create
。
答案 1 :(得分:0)
您使用entry
3次,看起来像是一个错误。
File.open(playlist, 'a') do |f|
entry.each do |e|
f.puts "#{e.song} by #{e.artist} on #{e.album}"
end
end
答案 2 :(得分:0)
我认为这部分的错误是因为单引号字符串不支持字符串插值。
f.puts '#{e.song} by #{e.artist} on #{e.album}'
你能试试吗
f.puts "#{e.song} by #{e.artist} on #{e.album}"