How can I do a cross-model find in a way which conforms most closely to the MVC pattern?
I have a model, Istc.rb. In the index view that corresponds to this model, I want to do this:
= "Last edited by #{User.find_by_id(istc.user_id).first_name}"
Clearly you can’t have a model.find in a view – and not only is this a model.find, it’s a find on a different model. But how would you refactor this?
I’m nervous about having a helper like this because it’s still pretty close to the View layer:
module UsernameHelper
def user_name(model)
User.find_by_id(model.user_id) unless User.find_by_id(model.user_id).nil?
end
end
Is the way to do it to have a scope on User?
# User.rb
scope :lookup, lambda {|model| where("id = ?", model.user_id)}
# username_helper.rb
module UsernameHelper
def user_name(model)
User.lookup(model).first unless User.lookup(model).first.nil?
end
end
Or should the istcs_controller handle it? Or should there be a separate controller, which talks to both the Istc and User model?
Thoughts welcome, and I’d really like to see any sample applications which solve this sort of problem elegantly, too.
As Rasmus said, if we make use of association its a simple think,
User Model:
Istc Model:
view:
If you are not happy with this the following would be the alternate solutions,