views:

29

answers:

2

I would like to set a default value in a has_many through association.

Lets say I have three models:

People

Friends

Dogs

A person can request that a dog becomes their friend.

So a person would create an association where friends has an active column = false.

User
  has_many :friends
  has_many :dogs, :through => :friends

Now when I assign a dog to a user

User.find(1).dogs << dog

The friends table has null in the active column.

My friends model is defined as

Friend
  def initialize(args = {})
    super(args)
    active = false
  end

yet this does not work because the friend object is never created. Do I have to manually create one?

+1  A: 

To set default values of a model; In the model I do this

    before_save :default_values

    private
    def default_values
      self.status = :active unless self.status
    end

Not sure if this is the correct approach though.

Ram
+1  A: 

With the following code you'll create a new friend with active = false

class User < ActiveRecord::Base
  has_many :friends, :conditions => "active = false"
  has_many :dogs, :through => :friends
end

@user = User.new
@user.friends.create #or @user.friends.build
j.
I can't really do that because I need the other values for active for other reasons. I feel Ram's answer is a bit better suited.
Dmitriy Likhten