一般来说,我会回答你的AcitveRecord对象可以包含任何字段,并且您在视图中显示只想要什么。脚本脚本中有脚手架任务,但只能创建一些设置模型,控制器和视图。当我使用Rails时,我根本不使用./script/generate scaffold
。相反,我只是分别生成模型和控制器。视图部分我添加manualy。
ActiveRecord的唯一地图从数据库到一些不错的对象的数据。你用它来做什么取决于你。
根据演示文稿和业务规则之间的分离,我认为下面的例子会让你清楚如何在Rails中处理它。
对于发票的例子,我将创建一个视图是这样的:
<h1>Invoices</h1>
<table>
<tr>
<th>Invoice #</th>
<th>Date</th>
<th>Name</th>
<th>No. of line items</th>
etc
</tr>
<% @invoices.each do |invoice| %>
<tr>
<td><%= invoice.number %></td>
<td><%= invoice.date.to_s %></td>
<td><%= invoice.name %></td>
<td><%= invoice.line_items.count %></td>
etc.
</tr>
<% end %>
</table>
甚至把带发票数据的行成独立的部分,呈现在上述观点。我假设你的模型中有:
# Invoice model
has_many :line_items
现在让我们来看看信用卡示例。当你使这个信用卡
# In CreditCard model add method
def fraudulent?
#put here some logic that returns true or false
end
然后在您的视图:
<div <%= @credit_card.fraudulent? ? 'class="show_in_red"' : '' %>
here you can show whatever you want
</div>
甚至创造帮手吧:
# credit card helper
def add_show_in_red(credit_card)
credit_card.fraudulent? ? 'class="show_in_red"' : ''
end
# in Rails 3 or earlier version with plugin that puts `h` method by default
# your helper should have additional safe_html! call
def add_show_in_red(credit_card)
(credit_card.fraudulent? ? 'class="show_in_red"' : '').safe_html!
end
,并鉴于我会做这样的:
<div <%= add_show_in_red(@credit_card) %>>
here you can show whatever you want
</div>
我不来自.NET的背景,也许我不是这样很好 - 我不明白你的问题。你能举一些例子吗? – klew 2010-02-23 23:24:34
我发现你的问题非常有用,清晰并且专注,但是我不认为_DTO_是你描述的正确的术语。 DTO是_Data Transfer Object_,它是客户端 - 服务器体系结构中用于在客户端和服务器之间交换的通信对象的术语,而您所描述的内容通常称为_ViewModel_,即为绑定而定制的模型一个看法。 – 2014-02-13 17:36:57