How do I find stuff with habtm associations?

Hi,

I’m having trouble with rails bailing out on me when using find on an
habtm association. I’m trying to do a digg clone (as you might see). The
following code is simplified:

the news_posts_users table is set up correctly

class NewsPost < ActiveRecord::Base
has_and_belongs_to_many :diggs, :class_name => ‘User’
end

class User < ActiveRecord::Base
has_and_belongs_to_many :diggs, :class_name => ‘NewsPost’
end

class NewsController < ApplicationController
def digg
@user = get_current_user
@post = NewsPost.find_by_name(params[:name])

# i want to check if user has already "dugg" the news item
# this doesn't work though, look at the final comment
unless @post.diggs.find(@user.id)
  if @post.diggs << @user
    notice_redirect 'News item dugg', news_url(:name => @post.name)
    return
  end
end
notice_redirect 'News item already dugg', news_url(:name => 

@post.name)
end
end

when the user has already dugg the news item (i added the

db stuff manually to test) the unless test works fine.

however, when the user hasn’t dugg the item rails spits out:

ActiveRecord::RecordNotFound in NyheterController#hajpa

Couldn’t find User with ID=1 AND (news_posts_users.news_post_id = 5 )

etc.

where am I going wrong? :frowning:

Best regards,
Malte

I solved it by doing “unless @post.diggs.find(:first, :conditions =>
[‘user_id = ?’, @user.id])” instead of “@post.diggs.find(@user.id)”.

The latter incidently generates the same SQL as the former. This looks
like a rather serious bug, or am I missing something?

Best regards,
Malte

Malte Obbel Forsberg wrote:

Hi,

I’m having trouble with rails bailing out on me when using find on an
habtm association. I’m trying to do a digg clone (as you might see). The
following code is simplified:

the news_posts_users table is set up correctly

class NewsPost < ActiveRecord::Base
has_and_belongs_to_many :diggs, :class_name => ‘User’
end

class User < ActiveRecord::Base
has_and_belongs_to_many :diggs, :class_name => ‘NewsPost’
end

class NewsController < ApplicationController
def digg
@user = get_current_user
@post = NewsPost.find_by_name(params[:name])

# i want to check if user has already "dugg" the news item
# this doesn't work though, look at the final comment
unless @post.diggs.find(@user.id)
  if @post.diggs << @user
    notice_redirect 'News item dugg', news_url(:name => @post.name)
    return
  end
end
notice_redirect 'News item already dugg', news_url(:name => 

@post.name)
end
end

when the user has already dugg the news item (i added the

db stuff manually to test) the unless test works fine.

however, when the user hasn’t dugg the item rails spits out:

ActiveRecord::RecordNotFound in NyheterController#hajpa

Couldn’t find User with ID=1 AND (news_posts_users.news_post_id = 5 )

etc.

where am I going wrong? :frowning:

Best regards,
Malte