这不完全是一个问题,而是关于我如何解决问题的报告write_attribute
当属性是一个对象时,在 Rails 上Active Record
。我希望这对面临同样问题的其他人有用。
让我用一个例子来解释一下。假设你有两个班级,Book
and Author
:
class Book < ActiveRecord::Base
belongs_to :author
end
class Author < ActiveRecord::Base
has_many :books
end
很简单。但是,无论出于何种原因,您都需要覆盖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
不幸的是,这不起作用。这就是我从控制台得到的:
>> 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, updated_at: nil>
>> book.author = "Lewis Carroll"
=> "Lewis Carroll"
>> book
=> #<Book id: nil, name: "Alice's Adventures in Wonderland", pub_year: 1865, author_id: nil, created_at: nil, updated_at: nil>
>> book.author
=> nil
看来 Rails 不承认它是一个对象并且什么也没做:在归属之后,author 仍然是 nil!当然,我可以尝试write_attribute(:author_id, author.id)
,但是当作者尚未保存时(它仍然没有 id!)并且我需要将对象保存在一起(只有当书籍有效时才必须保存作者),这没有帮助。
在搜索了很多解决方案之后(并徒劳地尝试了许多其他事情),我发现了这条消息:http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/4fe057494c6e23e8 http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/4fe057494c6e23e8,所以最后我可以得到一些工作代码:
class Book < ActiveRecord::Base
belongs_to :author
def author_with_lookup=(author)
author = Author.find_or_initialize_by_name(author) if author.is_a? String
self.author_without_lookup = author
end
alias_method_chain :author=, :lookup
end
这一次,控制台对我来说很好:
>> 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, updated_at: nil>
>> book.author = "Lewis Carroll"=> "Lewis Carroll"
>> book
=> #<Book id: nil, name: "Alice's Adventures in Wonderland", pub_year: 1865, author_id: nil, created_at: nil, updated_at: nil>
>> book.author
=> #<Author id: nil, name: "Lewis Carroll", created_at: nil, updated_at: nil>
这里的技巧是alias_method_chain
,这会创建一个拦截器(在本例中author_with_lookup
)和旧设置器的替代名称(author_without_lookup
)。我承认花了一些时间来理解这种安排,如果有人愿意详细解释它,我会很高兴,但令我惊讶的是缺乏有关此类问题的信息。我必须在谷歌上进行大量搜索才能找到一篇文章,从标题来看,该文章最初似乎与问题无关。我是 Rails 新手,所以你们觉得伙计们怎么样:这是一个不好的做法吗?