2015-10-04 102 views
1

我一直在自学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 

回答

2

你有4个错误的位置:

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 
  1. |entry|打开Fileplaylist.txt)的实例在这里,不是Entry实例类。语法是正确的(文件打开正确),但似乎有一些混淆(逻辑错误)。
  2. 您想要参考创建的Entry模型,您需要通过实例变量@entry来完成此操作,或者,最好将其作为参数传递给函数save_to_file。由于entry引用1个对象而不是集合,因此您不需要each
  3. f没有定义,所以试图调用任何方法会导致错误。你可能打算在这里使用p.1的变量。
  4. 字符串插值(如"#{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方法称呼其为save_to_file(@entry)

+1

我无法感谢您的耐心和周到的答复。我很确定我的错误在方法参数或基本逻辑的某处存在,但是有足够的错误导致我无法调试它。非常感谢你。 – jirgens

+0

非常欢迎:) –

0

您使用entry 3倍,它看起来像一个bug。

File.open(playlist, 'a') do |f| 
    entry.each do |e| 
    f.puts "#{e.song} by #{e.artist} on #{e.album}" 
    end 
end 
+0

我一直没有使用Rails的年龄,但不应该这'Entry.each'迭代'Entry'类的实例? –

0

由于我认为这部分错误,因为单引号字符串不支持字符串插值。

f.puts '#{e.song} by #{e.artist} on #{e.album}' 

难道你试试这个

f.puts "#{e.song} by #{e.artist} on #{e.album}" 
相关问题