新手问题 我想请教几个 Ruby 和 Rails 的问题.希望有人能指点下.

liudongyue1987 · February 13, 2016 · Last by safir replied at February 15, 2016 · 2265 hits

本人之前是做C#开发的.现在在学习ruby和rails的过程中遇到一些问题,实在想不明白.希望有人能指点下.万分感谢. 1,rails 中自定义的 对象 应该放在哪个文件下?models 下吗? 我的这个对象只是用来方便处理业务数据的。不和数据库交互。

2,我有下面这个对象

这是 ruby 中定义对象的形式:

class MyModel
    attributes :key, :name, :name_value
end

下面这个是在C#中定义对象的形式:

public class MyModel
{
   public string key {get;set;}
   public string name {get;set;}
   public string name_value {get;set;}
}

在C#中,我可以使用List 来存储 MyModel 这个对象的集合 然后可以使用 linq 方便的查询这个 List 比如:

List<MyModel> myModelList = new List<MyModel>();
List<MyModel> result = myModelList.Where(tmp=>tmp.key=="a");

我现在纠结的是: ruby 中如何实现这个功能?用数组么? C#的linq写法已经根深蒂固.在纠结中.

1. 可以放在 app/models,或者在 app/ 下新建目录:

# app/services/my_service.rb
class MyService
end

类名要对应文件名,不然 Rails 不会自动加载。services 也可以是别的名字。

2. 用数组

list = []
list.push MyModel.new
result = list.find_all{|item| item.key == 'a'}

但是 Ruby 的列表没有类型声明,会不会 push 进了别的对象要靠自己的代码保证。

自己新建一个文件夹,放 app/下,rails 好像不会自动加载吧?如果要放,得在 application.rb 文件里面把文件夹路径加到 autoload_paths 数组里面。或者把跟数据库无关的类似模型的文件放到 model/concerns 下面吧。

#2 楼 @happyming9527

All subdirectories of app in the application and engines. For example, app/controllers. They do not need to be the default ones, any custom directories like app/workers belong automatically to autoload_paths.

http://guides.rubyonrails.org/autoloading_and_reloading_constants.html#autoload-paths

#1 楼 @rei 感谢回答。解决了我的疑惑。

如果资料表中有 3 个主键 user_id、product_id 和 flag 那么需要怎么写联合索引和 unique?

You need to Sign in before reply, if you don't have an account, please Sign up first.