I found myself writing the following piece of code over and over again:
MyModel.find(my_id).my_field
I wonder if 开发者_StackOverflowthere is a simpler method to write this ?
If you are asking if there is more concise way of writing that.. not sure there is with the standard finders. What you have is pretty small. Just for fun I wrote this for you though :)
class ActiveRecord::Base
def self.method_missing_with_retrieve_just_a_field(method_called, *args, &block)
if(method_called.to_s=~/get_/)
self.find(args[0]).send(method_called.to_s.gsub("get_", ""))
else
method_missing_without_retrieve_just_a_field(method_called, *args, &block)
end
end
class << self
alias_method_chain :method_missing, :retrieve_just_a_field
end
end
If you put this in your config/initializers as some file like crazy_finder.rb you can then just say:
MyModel.get_my_field(my_id)
It doesnt save you much, but just thought it would be fun to write.
In addition to Jake's global solution for every model and every attribute, you can easily define explicit individual accessors:
class MyModel
def self.my_field(id)
find(id).my_field
end
end
Or an array of fields:
class MyModel
class << self
[:my_field, :other_field].each do |field|
define_method field do |id|
find(id).send(field)
end
end
end
end
Are you doing this for same resource over and over again or to many different resources? It would really help if you'd give us better example of what you're trying to do, if you're doing that many times, it would help to give us example of what you're doing many times.
If you're doing this for one resource only to get different values:
If you're doing this in same action over and over again, you're doing it wrong. First store your result in a variable like this:
@mymodel = MyModel.find(id)
and then you can use
@mymodel.my_field
and then again (without the need to find it again)
@mymodel.different_field
or if you want to do this for a collection you can do:
@mymodels = MyModel.find([my_first_id, my_second_id, my_third_id])
etc.. better example from your side would help to help you!
精彩评论