【问题标题】:Ruby DataMapper, table inheritanceRuby DataMapper,表继承
【发布时间】:2013-09-11 05:34:55
【问题描述】:

我的表格总是重复这一行

    property :created_at, DateTime, :default => DateTime.now, :lazy => [:show]
property :updated_at, DateTime, :default => DateTime.now, :lazy => [:show]

如何将其干燥?我是继承,还是拥有一个模块,还是别的什么?

是这样的:

Class Foo
include DataMapper::Resource

property :id, Int
property :created_at, DateTime, :default => DateTime.now, :lazy => [:show]
property :updated_at, DateTime, :default => DateTime.now, :lazy => [:show]
end

Class Bar
include DataMapper::Resource

property :id, Int
property :created_at, DateTime, :default => DateTime.now, :lazy => [:show]
property :updated_at, DateTime, :default => DateTime.now, :lazy => [:show]
end

这些在每个表格中重复多次

【问题讨论】:

  • 我需要更多信息。该日志何时/何地显示?是在控制台里面吗?在模型里面?请试着解释得更好一点。
  • @GuilhermeBarrosAvila 更新了帖子。我不断地重复这些领域。不确定是模块、类还是其他任何东西。如果你不介意我问,我还有一个问题:如何创建一个在整个数据库创建后执行的函数?例如,在创建数据库及其所有表之后,我想添加一些视图。我该怎么做?
  • 对此做出了回答。喜欢就标记为对,希望能帮到你。

标签: ruby-on-rails ruby ruby-datamapper


【解决方案1】:

嗯,现在我明白你在说什么了。这些是自动创建的 rails 属性。我不确定是否有办法防止这种情况发生,但这些在许多情况下肯定有用。我建议您保留它们,当您了解更多有关 Rails 的信息时,您将了解它们的用途。

对于视图,您需要创建一个控制器方法并在config/routes.rb 中定义这些方法的路由。我建议您了解有关 MVC 导轨模式的更多信息。 MVC 是构建 Rails 的核心。

http://guides.rubyonrails.org/ 是一个很棒的学习rails 网站。尝试只阅读几篇文章,您将能够理解到足以立即构建完整的应用程序。

【讨论】:

  • 我没有足够的关于 Sinatra 的知识来回答你。尽管知道它是如何工作的以及应该如何完成,但我认为最好还是在互联网上寻找教程和书籍
【解决方案2】:

我正在做类似的事情。我像这样使用继承:

require 'rubygems'
require 'dm-core'
require 'dm-migrations'
require 'dm-constraints'

DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/development.db")
DataMapper::Property::String.length(255)

class BaseTable
  include DataMapper::Resource
  property :id, Serial
  property :created_date, DateTime, :default => DateTime.now
  property :created_by, Integer
  property :updated_date, DateTime, :default => DateTime.now
  property :updated_by, Integer
end

class User < BaseTable
  property :userid, String
  property :email, String
  property :password, String
end

class Account < BaseTable
  property :name, String
  property :type, String
  property :location, String
  property :account_number, String
  property :total_balance, Integer
  property :cleared_balance, Integer
  property :marked_as_cleared_balance, Integer
  has n, :transactions, :constraint => :destroy
end

class Transaction < BaseTable
  property :id, Serial
  property :label, String
  property :cleared, Boolean
  property :date, Date
  property :description, String
  property :amount, Integer
  property :note, String
  property :balance, Integer
  belongs_to :account
end

DataMapper.finalize
DataMapper.auto_upgrade!

【讨论】:

    猜你喜欢
    • 2010-12-22
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多