Topic: find_or_create usage

I've got a create action thats trying to find_or_create a Channel and then add the creator as a member, I checked the api but couldnt figure if the following would be possible:


works just fine, what I'm looking for is if theres already a way to do something in the lines of
find_by_name_or_create(params[:channel][:name], params[:channel])

or will I have to write it as a custom method?

Re: find_or_create usage

That's not currently supported by ActiveRecord but you can easily write it yourself.  The only trick I can think of is that create usually takes a hash while find_by_name just takes a string.
Maybe something like this would work:

def find_by_name_or_create(arg)
  if arg.is_a? String
  elsif arg.is_a? Hash
    find_by_name(arg[:name]) || create(arg)

Re: find_or_create usage

nice, I figured the implementation wouldnt be that hard to do, was just checking if there already was one in place wink

I'm guessing that should be

def self.find_by_name_or_create(arg)

as I'm using it with the channel class instead of instances.

Theres one a bit offtopic question on my mind but I'll throw that one here also, I'm wondering if this is the best way to save a membership during channel creation/finding, as memberships belongs_to :channels and :users

    @channel = Channel.find_by_name_or_create(params[:channel])
    @member =
    current_user.memberships << @member

I'm just desperately trying to avoid using something as bulky as
@member.user_id =

and I guess It'd be good to know for the future, as it seems multiple belongs_to creates are piling up in my app. If thats the best way to do a double belongs_to, how should it be modified for, say, three of them?