这不是一个问题,而是一个关于我如何write_attribute在Rails 上解决属性是一个对象的问题的报告Active Record.我希望这对面临同样问题的其他人有用.
让我举个例子来解释一下.假设您有两个类,Book并且Author:
class Book < ActiveRecord::Base
belongs_to :author
end
class Author < ActiveRecord::Base
has_many :books
end
Run Code Online (Sandbox Code Playgroud)
非常简单.但是,无论出于何种原因,您需要覆盖author=方法Book.由于我是Rails的新手,我遵循了Sam Ruby关于使用Rails进行敏捷Web开发的建议:使用attribute_writer私有方法.所以,我的第一次尝试是:
class Book < ActiveRecord::Base
belongs_to :author
def author=(author)
author = Author.find_or_initialize_by_name(author) if author.is_a? String
self.write_attribute(:author, author)
end
end
Run Code Online (Sandbox Code Playgroud)
不幸的是,这不起作用.这就是我从控制台得到的:
>> book = Book.new(:name => "Alice's Adventures in Wonderland", :pub_year => 1865)
=> #<Book id: nil, name: "Alice's Adventures in Wonderland", pub_year: 1865, author_id: nil, created_at: nil, …Run Code Online (Sandbox Code Playgroud) 我需要将一组数据从一个表复制到另一个包含BLOB列的数据.我正在使用INSERT子查询的查询SELECT:
INSERT INTO dest_table(field1,field2,field3,blobfield,field4) (SELECT t.myfield1,t.myfield2,t.id,t.blobfield,'SomeConstant' FROM tablename t)
Run Code Online (Sandbox Code Playgroud)
所有字段都被正确复制,除了BLOB.我知道我错过了什么,但我不知道如何做这项工作.搜索没有帮助我.有谁知道如何解决它?
我更喜欢纯SQL的解决方案,但我也可以使用Ruby.
是否有一些库或助手用Ruby生成SVG图形?我google了一下,发现了很多,但似乎都尘土飞扬,非常不完整......有谁知道一些不错的,可靠的替代方案?
我需要将文件布局上的固定宽度字段与正则表达式匹配.该字段为数字/整数,始终包含四个字符,包含在0..1331范围内.当数字小于1000时,字符串用左零填充.所以这些例子都是有效的:
但下面必须不能接受:
如果我只能用正则表达式强制实施这个限制,那就太好了.玩了一会后,我得出了表达\0*[0-1331]\.问题是它不会将大小限制为四个字符.我当然可以做,\000[0-9]|00[10-99]|0[100-999]|[1000-1331]\但我拒绝使用如此令人讨厌的东西.谁能想到更好的方法?
我工作的一Chart类,它有一个margin参数,保存:top,:bottom,:right和:left值.我的第一个选择是创建margin一个setter并设置如下值:
# Sets :left and :right margins and doesn't alter :top and :bottom
chart.margins = {:left => 10, :right => 15}
Run Code Online (Sandbox Code Playgroud)
这很好,因为它显然是一个制定者,但是,经过一番思考,我认为它也可能令人困惑:用户可能认为边距只包含:left和:right值,什么是不对的.另一种选择是消除=并使其成为一种普通的方法:
chart.margins(:left => 10, :right => 15)
Run Code Online (Sandbox Code Playgroud)
使用这种语法,很容易弄清楚发生了什么,但它不是标准的setter并且与marginsgetter 冲突.而且还有另一种选择:
chart.margins(:left, 10)
chart.margins(:right, 15)
Run Code Online (Sandbox Code Playgroud)
我不知道该怎么想.对我来说,很明显这个方法是一个setter,但这次我不能只用一次调用设置多个值,而getter又有问题.我对Ruby比较陌生,我还没有习惯所有的习语.所以,你觉得男人们怎么样?哪个是最好的选择?
程序员队友.我用一个非常简单的代码测试java线程功能(或者至少看起来很简单).我有这个班级帐号:
public class Account {
protected double balance;
public synchronized void withdraw(double value) {
this.balance = this.balance - value;
}
public synchronized void deposit(double value) {
this.balance = this.balance + value;
}
public synchronized double getBalance() {
return this.balance;
}
}
Run Code Online (Sandbox Code Playgroud)
我有两个主题:Depositer一千万次存款10美元:
public class Depositer extends Thread {
protected Account account;
public Depositer(Account a) {
account = a;
}
@Override
public void run() {
for(int i = 0; i < 1000; i++) {
this.account.deposit(10);
}
} …Run Code Online (Sandbox Code Playgroud)