Hi,
My work with Rails has been fairly straightforward, until yesterday…
I’ve encountered rather a peculiar problem that I’m not able to solve
myself as a rails-newbie.
The model code looks like this:
class Link < ActiveRecord::Base
has_one :user_vote
end
class UserVote < ActiveRecord::Base
belongs_to :user
belongs_to :link
end
I have a SQL query that is responsible for pulling out all links along
with votes from a database:
links = Link.find_by_sql(
[“SELECT * FROM links LEFT JOIN user_votes ON links.id =
user_votes.link_id” +
" AND user_votes.user_id = ?", session[:user_id]]
)
If a user hadn’t voted for a given link yet, an empty record is returned
(NULL). The problem is that when trying to call that unexisting
associated object (link.user_vote) Rails attempts to retrieve it from
the database. This can result in getting a vote that belongs to another
user.
Is it possible to disable the lazy-loading feature for that particular
association?
Is there any other way to perform the above-mentioned JOIN without using
find_by_sql?
thanks in advance,
Piotr Chmolowski