有没有办法撤消/还原对Activerecord对象的任何本地更改.例如:
user = User.first
user.name # "Fred"
user.name = "Sam"
user.name_was # "Fred"
user.revert
user.name # "Fred"
Run Code Online (Sandbox Code Playgroud)
我知道我可以这样做,user.reload但我不应该在数据库中执行此操作,因为旧值存储在对象的状态中.
优选Rails 3解决方案.
我想使用Ruby方法生成在我的页面中经常出现的标记.本质上,我想做相当于此(ERB文件):
<% def create_button(text) %>
<div class="button"><%= text %></div>
<% end %>
...
<%
create_button("My First Button")
create_button("My Second Button")
# etc.
%>
Run Code Online (Sandbox Code Playgroud)
显然,我的想法是,每当我需要一个按钮时,我就会使用create_button.
我想象的Ruby/HAML解决方案看起来像这样:
def create_button(text)
%div.button text
end
create_button("My First Button")
create_button("My Second Button")
Run Code Online (Sandbox Code Playgroud)
此输出将与第一个块相同.
有没有办法做到这一点?如果没有,最终我正在寻找一种使用Ruby辅助方法生成标记的优雅方法.如果您对如何做到这一点有任何建议,我想听听.我是Rails的新手并不喜欢ERB,但也许我错过了一些东西.无论如何,我愿意接受建议.
我不太确定如何很好地提出这个问题。抱歉,如果不清楚。我正在尝试确定对象所充当的类型,而不是对象的实际类型。
说我有这两个类:
public class A{
public A() {
string thisTypeName = this.GetType().???; // the value I'm looking for here is "A" not "B"
}
}
public class B : A { }
Run Code Online (Sandbox Code Playgroud)
我不想要的是...
string thisTypeName = this.GetType().BaseType.Name;
Run Code Online (Sandbox Code Playgroud)
......因为如果我决定这样做......
public class C : B { }
Run Code Online (Sandbox Code Playgroud)
...那么现在我的 this.GetType().BaseType 将引用类 B,而不是 A。
有没有内置的方法来做到这一点?我猜我可以在 Type 上写一个扩展方法来做我想做的事。