views:

309

answers:

2

Hello, I have a model, Feed, that has and belongs to many FilteredUsers. In this case I have implemented it through a has_many :through relationship.

class Feed < ActiveRecord::Base
  has_many :denials, :dependent => :destroy
  has_many :filtered_users, :through => :denials

I would like to create a record if it doesn't exist or find the object if it does exist. When I try and use the find_or_initialize_by (or find_or_create_by) an exception is thrown saying undefined method 'feed_id=' for <FilteredUser..

Here is the code:

feed = Feed.find(params[:id])
user = feed.filtered_users.find_or_initialize_by_user_url(params[:user_url])
if params[:status] == "block"
  feed.filtered_users << user
else
  feed.filtered_users.delete(user)
end
feed.save

Any suggestions on how to fix this or how to work around it DRYly?

Thanks!

A: 

Wouldn't it be easier to check the params[:status] first and then do what you need to do?

feed = Feed.find(params[:id])
if params[:status] == 'block'
   feed.filtered_users.build(:user_url => params[:user_url])
else
   feed.filtered_users.find_by_user_url(params[:user_url]).delete
end
feed.save

warning this is air coded not tested

ErsatzRyan
+1  A: 

First, because it's a has_many :through relationship, the initialization has no way of knowing which denial the new filtered_user should be associated with. If you want to use find_or_initialize_by, you need to run it on a specific denial that is associated with the feed.

Build a new filtered_user and associate it with a specific denial.

Second, agreeing with ErsatzRyan, the general logic seems a bit off.

Ryan McGeary