在介绍CSV文件的读写方法前,我们需要了解一下CSV文件的格式。
一个简单的CSV文件:
Test1,Test2,Test3,Test4,Test5,Test6
str1,str2,str3,str4,str5,str6
str1,str2,str3,str4,str5,str6
一个不简单的CSV文件:
"Test1
"",""","Test2
"",""","Test3
"",""","Test4
"",""","Test5
"",""","Test6
"","""
" 中文,D23 ","3DFD4234""""""1232""1S2","ASD1"",""23,,,,213
23F32","
",,asd
" 中文,D23 ","3DFD4234""""""1232""1S2","ASD1"",""23,,,,213
23F32","
",,asd
你没看错,上面两个都是CSV文件,都只有3行CSV数据。第二个文件多看一眼都是精神污染,但项目中无法避免会出现这种文件。
CSV文件没有官方的标准,但一般项目都会遵守 RFC 4180 标准。这是一个非官方的标准,内容如下:
- Each record is located on a separate line, delimited by a line break (CRLF).
- The last record in the file may or may not have an ending line break.
- There maybe an optional header line appearing as the first line of the file with the same format as normal record lines. This header will contain names corresponding to the fields in the file and should contain the same number of fields as the records in the rest of the file (the presence or absence of the header line should be indicated via the optional "header" parameter of this MIME type).
- Within the header and each record, there may be one or more fields, separated by commas. Each line should contain the same number of fields throughout the file. Spaces are considered part of a field and should not be ignored. The last field in the record must not be followed by a comma.
- Each field may or may not be enclosed in double quotes (however some programs, such as Microsoft Excel, do not use double quotes at all). If fields are not enclosed with double quotes, then double quotes may not appear inside the fields.
- Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes.
- If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be escaped by preceding it with another double quote.
翻译一下:
上面的标准可能比较拗口,我们对它进行一些简化。要注意一下,简化不是简单的删减规则,而是将类似的类似进行合并便于理解。
后面的代码也会使用简化标准,简化标准如下:
每条记录位于单独的行上,由换行符 (CRLF) 分隔。
注:此处的行不是普通文本意义上的行,是指符合CSV文件格式的一条记录(后面简称为CSV行),在文本上可能占据多行。
文件中的最后一条记录需有结束换行符,文件的第一行为标题行(标题行包含字段对应的名称,标题数与记录的字段数相同)。
注:原标准中可有可无的选项统一规定为必须有,方便后期的解析,而且没有标题行让别人怎么看数据。
在标题和每条记录中,可能有一个或多个字段,以逗号分隔。在整个文件中,每行应包含相同数量的字段。空格被视为字段的一部分,不应忽略。记录中的最后一个字段后面不能有逗号。
注:此标准未做简化,虽然也有其它标准使用空格、制表符等做分割的,但不使用逗号分割的文件还叫逗号分隔值文件吗。
每个字段都用双引号括起来,出现在字段中的双引号必须在其前面加上另一个双引号
注:原标准有必须使用双引号和可选双引号的情况,那全部使用双引号肯定不会出错。*
在正式读写CSV文件前,我们需要先定义一个用于测试的Test类。代码如下:
class Test
{
public string Test1{get;set;}
public string Test2 { get; set; }
public string Test3 { get; set; }
public string Test4 { get; set; }
public string Test5 { get; set; }
public string Test6 { get; set; }
//Parse方法会在自定义读写CSV文件时用到
public static Test Parse (string[]fields )
{
try
{
Test ret = new Test();
ret.Test1 = fields[0];
ret.Test2 = fields[1];
ret.Test3 = fields[2];
ret.Test4 = fields[3];
ret.Test5 = fields[4];
ret.Test6 = fields[5];
return ret;
}
catch (Exception)
{
//做一些异常处理,写日志之类的
return null;
}
}
}
生成一些测试数据,代码如下:
static void Main(string[] args)
{
//文件保存路径
string path = "tset.csv";
//清理之前的测试文件
File.Delete("tset.csv");
Test test = new Test();
test.Test1 = " 中文,D23 ";
test.Test2 = "3DFD4234\"\"\"1232\"1S2";
test.Test3 = "ASD1\",\"23,,,,213\r23F32";
test.Test4 = "\r";
test.Test5 = string.Empty;
test.Test6 = "asd";
//测试数据
var records = new List<Test> { test, test };
//写CSV文件
/*
*直接把后面的写CSV文件代码复制到此处
*/
//读CSV文件
/*
*直接把后面的读CSV文件代码复制到此处
*/
Console.ReadLine();
}
CsvHelper 是用于读取和写入 CSV 文件的库,支持自定义类对象的读写。
github上标星最高的CSV文件读写C#库,使用MS-PL、Apache 2.0开源协议。
使用NuGet下载CsvHelper,读写CSV文件的代码如下:
//写CSV文件
using (var writer = new StreamWriter(path))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.WriteRecords(records);
}
using (var writer = new StreamWriter(path,true))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
//追加
foreach (var record in records)
{
csv.WriteRecord(record);
}
}
//读CSV文件
using (var reader = new StreamReader(path))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
records = csv.GetRecords<Test>().ToList();
//逐行读取
//records.Add(csv.GetRecord<Test>());
}
如果你只想要拿来就能用的库,那文章基本上到这里就结束了。
为了与CsvHelper区分,新建一个CsvFile类存放自定义读写CSV文件的代码,最后会提供类的完整源码。CsvFile类定义如下:
/// <summary>
/// CSV文件读写工具类
/// </summary>
public class CsvFile
{
#region 写CSV文件
//具体代码...
#endregion
#region 读CSV文件(使用TextFieldParser)
//具体代码...
#endregion
#region 读CSV文件(使用正则表达式)
//具体代码...
#endregion
}
根据简化标准(具体标准内容见前文),写CSV文件代码如下:
#region 写CSV文件
//字段数组转为CSV记录行
private static string FieldsToLine(IEnumerable<string> fields)
{
if (fields == null) return string.Empty;
fields = fields.Select(field =>
{
if (field == null) field = string.Empty;
//简化标准,所有字段都加双引号
field = string.Format("\"{0}\"", field.Replace("\"", "\"\""));
//不简化标准
//field = field.Replace("\"", "\"\"");
//if (field.IndexOfAny(new char[] { ',', '"', ' ', '\r' }) != -1)
//{
// field = string.Format("\"{0}\"", field);
//}
return field;
});
string line = string.Format("{0}{1}", string.Join(",", fields), Environment.NewLine);
return line;
}
//默认的字段转换方法
private static IEnumerable<string> GetObjFields<T>(T obj, bool isTitle) where T : class
{
IEnumerable<string> fields;
if (isTitle)
{
fields = obj.GetType().GetProperties().Select(pro => pro.Name);
}
else
{
fields = obj.GetType().GetProperties().Select(pro => pro.GetValue(obj)?.ToString());
}
return fields;
}
/// <summary>
/// 写CSV文件,默认第一行为标题
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">数据列表</param>
/// <param name="path">文件路径</param>
/// <param name="append">追加记录</param>
/// <param name="func">字段转换方法</param>
/// <param name="defaultEncoding"></param>
public static void Write<T>(List<T> list, string path,bool append=true, Func<T, bool, IEnumerable<string>> func = null, Encoding defaultEncoding = null) where T : class
{
if (list == null || list.Count == 0) return;
if (defaultEncoding == null)
{
defaultEncoding = Encoding.UTF8;
}
if (func == null)
{
func = GetObjFields;
}
if (!File.Exists(path)|| !append)
{
var fields = func(list[0], true);
string title = FieldsToLine(fields);
File.WriteAllText(path, title, defaultEncoding);
}
using (StreamWriter sw = new StreamWriter(path, true, defaultEncoding))
{
list.ForEach(obj =>
{
var fields = func(obj, false);
string line = FieldsToLine(fields);
sw.Write(line);
});
}
}
#endregion
使用时,代码如下:
//写CSV文件
//使用自定义的字段转换方法,也是文章开头复杂CSV文件使用字段转换方法
CsvFile.Write(records, path, true, new Func<Test, bool, IEnumerable<string>>((obj, isTitle) =>
{
IEnumerable<string> fields;
if (isTitle)
{
fields = obj.GetType().GetProperties().Select(pro => pro.Name + Environment.NewLine + "\",\"");
}
else
{
fields = obj.GetType().GetProperties().Select(pro => pro.GetValue(obj)?.ToString());
}
return fields;
}));
//使用默认的字段转换方法
//CsvFile.Write(records, path);
你也可以使用默认的字段转换方法,代码如下:
CsvFile.Save(records, path);
TextFieldParser是VB中解析CSV文件的类,C#虽然没有类似功能的类,不过可以调用VB的TextFieldParser来实现功能。
TextFieldParser解析CSV文件的代码如下:
#region 读CSV文件(使用TextFieldParser)
/// <summary>
/// 读CSV文件,默认第一行为标题
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="path">文件路径</param>
/// <param name="func">字段解析规则</param>
/// <param name="defaultEncoding">文件编码</param>
/// <returns></returns>
public static List<T> Read<T>(string path, Func<string[], T> func, Encoding defaultEncoding = null) where T : class
{
if (defaultEncoding == null)
{
defaultEncoding = Encoding.UTF8;
}
List<T> list = new List<T>();
using (TextFieldParser parser = new TextFieldParser(path, defaultEncoding))
{
parser.TextFieldType = FieldType.Delimited;
//设定逗号分隔符
parser.SetDelimiters(",");
//设定不忽略字段前后的空格
parser.TrimWhiteSpace = false;
bool isLine = false;
while (!parser.EndOfData)
{
string[] fields = parser.ReadFields();
if (isLine)
{
var obj = func(fields);
if (obj != null) list.Add(obj);
}
else
{
//忽略标题行业
isLine = true;
}
}
}
return list;
}
#endregion
使用时,代码如下:
//读CSV文件
records = CsvFile.Read(path, Test.Parse);
如果你有一个问题,想用正则表达式来解决,那么你就有两个问题了。
正则表达式有一定的学习门槛,而且学习后不经常使用就会忘记。正则表达式解决的大多数是一些不易变更需求的问题,这就导致一个稳定可用的正则表达式可以传好几代。
本节的正则表达式来自 《精通正则表达式(第3版)》 第6章 打造高效正则表达式——简单的消除循环的例子,有兴趣的可以去了解一下,表达式说明如下:

注:这本书最终版的解析CSV文件的正则表达式是Jave版的使用占有优先量词取代固化分组的版本,也是百度上经常见到的版本。不过占有优先量词在C#中有点问题,本人能力有限解决不了,所以使用了上图的版本。不过,这两版正则表达式性能上没有差异。
正则表达式解析CSV文件代码如下:
#region 读CSV文件(使用正则表达式)
/// <summary>
/// 读CSV文件,默认第一行为标题
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="path">文件路径</param>
/// <param name="func">字段解析规则</param>
/// <param name="defaultEncoding">文件编码</param>
/// <returns></returns>
public static List<T> Read_Regex<T>(string path, Func<string[], T> func, Encoding defaultEncoding = null) where T : class
{
List<T> list = new List<T>();
StringBuilder sbr = new StringBuilder(100);
Regex lineReg = new Regex("\"");
Regex fieldReg = new Regex("\\G(?:^|,)(?:\"((?>[^\"]*)(?>\"\"[^\"]*)*)\"|([^\",]*))");
Regex quotesReg = new Regex("\"\"");
bool isLine = false;
string line = string.Empty;
using (StreamReader sr = new StreamReader(path))
{
while (null != (line = ReadLine(sr)))
{
sbr.Append(line);
string str = sbr.ToString();
//一个完整的CSV记录行,它的双引号一定是偶数
if (lineReg.Matches(sbr.ToString()).Count % 2 == 0)
{
if (isLine)
{
var fields = ParseCsvLine(sbr.ToString(), fieldReg, quotesReg).ToArray();
var obj = func(fields.ToArray());
if (obj != null) list.Add(obj);
}
else
{
//忽略标题行业
isLine = true;
}
sbr.Clear();
}
else
{
sbr.Append(Environment.NewLine);
}
}
}
if (sbr.Length > 0)
{
//有解析失败的字符串,报错或忽略
}
return list;
}
//重写ReadLine方法,只有\r\n才是正确的一行
private static string ReadLine(StreamReader sr)
{
StringBuilder sbr = new StringBuilder();
char c;
int cInt;
while (-1 != (cInt =sr.Read()))
{
c = (char)cInt;
if (c == '\n' && sbr.Length > 0 && sbr[sbr.Length - 1] == '\r')
{
sbr.Remove(sbr.Length - 1, 1);
return sbr.ToString();
}
else
{
sbr.Append(c);
}
}
return sbr.Length>0?sbr.ToString():null;
}
private static List<string> ParseCsvLine(string line, Regex fieldReg, Regex quotesReg)
{
var fieldMath = fieldReg.Match(line);
List<string> fields = new List<string>();
while (fieldMath.Success)
{
string field;
if (fieldMath.Groups[1].Success)
{
field = quotesReg.Replace(fieldMath.Groups[1].Value, "\"");
}
else
{
field = fieldMath.Groups[2].Value;
}
fields.Add(field);
fieldMath = fieldMath.NextMatch();
}
return fields;
}
#endregion
使用时代码如下:
//读CSV文件
records = CsvFile.Read_Regex(path, Test.Parse);
目前还未发现正则表达式解析有什么bug,不过还是不建议使用。
完整的CsvFile类代码如下:
using Microsoft.VisualBasic.FileIO;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApp4
{
/// <summary>
/// CSV文件读写工具类
/// </summary>
public class CsvFile
{
#region 写CSV文件
//字段数组转为CSV记录行
private static string FieldsToLine(IEnumerable<string> fields)
{
if (fields == null) return string.Empty;
fields = fields.Select(field =>
{
if (field == null) field = string.Empty;
//所有字段都加双引号
field = string.Format("\"{0}\"", field.Replace("\"", "\"\""));
//不简化
//field = field.Replace("\"", "\"\"");
//if (field.IndexOfAny(new char[] { ',', '"', ' ', '\r' }) != -1)
//{
// field = string.Format("\"{0}\"", field);
//}
return field;
});
string line = string.Format("{0}{1}", string.Join(",", fields), Environment.NewLine);
return line;
}
//默认的字段转换方法
private static IEnumerable<string> GetObjFields<T>(T obj, bool isTitle) where T : class
{
IEnumerable<string> fields;
if (isTitle)
{
fields = obj.GetType().GetProperties().Select(pro => pro.Name);
}
else
{
fields = obj.GetType().GetProperties().Select(pro => pro.GetValue(obj)?.ToString());
}
return fields;
}
/// <summary>
/// 写CSV文件,默认第一行为标题
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">数据列表</param>
/// <param name="path">文件路径</param>
/// <param name="append">追加记录</param>
/// <param name="func">字段转换方法</param>
/// <param name="defaultEncoding"></param>
public static void Write<T>(List<T> list, string path,bool append=true, Func<T, bool, IEnumerable<string>> func = null, Encoding defaultEncoding = null) where T : class
{
if (list == null || list.Count == 0) return;
if (defaultEncoding == null)
{
defaultEncoding = Encoding.UTF8;
}
if (func == null)
{
func = GetObjFields;
}
if (!File.Exists(path)|| !append)
{
var fields = func(list[0], true);
string title = FieldsToLine(fields);
File.WriteAllText(path, title, defaultEncoding);
}
using (StreamWriter sw = new StreamWriter(path, true, defaultEncoding))
{
list.ForEach(obj =>
{
var fields = func(obj, false);
string line = FieldsToLine(fields);
sw.Write(line);
});
}
}
#endregion
#region 读CSV文件(使用TextFieldParser)
/// <summary>
/// 读CSV文件,默认第一行为标题
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="path">文件路径</param>
/// <param name="func">字段解析规则</param>
/// <param name="defaultEncoding">文件编码</param>
/// <returns></returns>
public static List<T> Read<T>(string path, Func<string[], T> func, Encoding defaultEncoding = null) where T : class
{
if (defaultEncoding == null)
{
defaultEncoding = Encoding.UTF8;
}
List<T> list = new List<T>();
using (TextFieldParser parser = new TextFieldParser(path, defaultEncoding))
{
parser.TextFieldType = FieldType.Delimited;
//设定逗号分隔符
parser.SetDelimiters(",");
//设定不忽略字段前后的空格
parser.TrimWhiteSpace = false;
bool isLine = false;
while (!parser.EndOfData)
{
string[] fields = parser.ReadFields();
if (isLine)
{
var obj = func(fields);
if (obj != null) list.Add(obj);
}
else
{
//忽略标题行业
isLine = true;
}
}
}
return list;
}
#endregion
#region 读CSV文件(使用正则表达式)
/// <summary>
/// 读CSV文件,默认第一行为标题
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="path">文件路径</param>
/// <param name="func">字段解析规则</param>
/// <param name="defaultEncoding">文件编码</param>
/// <returns></returns>
public static List<T> Read_Regex<T>(string path, Func<string[], T> func, Encoding defaultEncoding = null) where T : class
{
List<T> list = new List<T>();
StringBuilder sbr = new StringBuilder(100);
Regex lineReg = new Regex("\"");
Regex fieldReg = new Regex("\\G(?:^|,)(?:\"((?>[^\"]*)(?>\"\"[^\"]*)*)\"|([^\",]*))");
Regex quotesReg = new Regex("\"\"");
bool isLine = false;
string line = string.Empty;
using (StreamReader sr = new StreamReader(path))
{
while (null != (line = ReadLine(sr)))
{
sbr.Append(line);
string str = sbr.ToString();
//一个完整的CSV记录行,它的双引号一定是偶数
if (lineReg.Matches(sbr.ToString()).Count % 2 == 0)
{
if (isLine)
{
var fields = ParseCsvLine(sbr.ToString(), fieldReg, quotesReg).ToArray();
var obj = func(fields.ToArray());
if (obj != null) list.Add(obj);
}
else
{
//忽略标题行业
isLine = true;
}
sbr.Clear();
}
else
{
sbr.Append(Environment.NewLine);
}
}
}
if (sbr.Length > 0)
{
//有解析失败的字符串,报错或忽略
}
return list;
}
//重写ReadLine方法,只有\r\n才是正确的一行
private static string ReadLine(StreamReader sr)
{
StringBuilder sbr = new StringBuilder();
char c;
int cInt;
while (-1 != (cInt =sr.Read()))
{
c = (char)cInt;
if (c == '\n' && sbr.Length > 0 && sbr[sbr.Length - 1] == '\r')
{
sbr.Remove(sbr.Length - 1, 1);
return sbr.ToString();
}
else
{
sbr.Append(c);
}
}
return sbr.Length>0?sbr.ToString():null;
}
private static List<string> ParseCsvLine(string line, Regex fieldReg, Regex quotesReg)
{
var fieldMath = fieldReg.Match(line);
List<string> fields = new List<string>();
while (fieldMath.Success)
{
string field;
if (fieldMath.Groups[1].Success)
{
field = quotesReg.Replace(fieldMath.Groups[1].Value, "\"");
}
else
{
field = fieldMath.Groups[2].Value;
}
fields.Add(field);
fieldMath = fieldMath.NextMatch();
}
return fields;
}
#endregion
}
}
使用方法如下:
//写CSV文件
CsvFile.Write(records, path, true, new Func<Test, bool, IEnumerable<string>>((obj, isTitle) =>
{
IEnumerable<string> fields;
if (isTitle)
{
fields = obj.GetType().GetProperties().Select(pro => pro.Name + Environment.NewLine + "\",\"");
}
else
{
fields = obj.GetType().GetProperties().Select(pro => pro.GetValue(obj)?.ToString());
}
return fields;
}));
//读CSV文件
records = CsvFile.Read(path, Test.Parse);
//读CSV文件
records = CsvFile.Read_Regex(path, Test.Parse);
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代
Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题
对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta
我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何