habtm foreign key must be manually done

I have a habtm relationship between User and Activity

when I create a new Activity why do I have to manually set the foreign key user_id in the activity table???

example

def create @activity = Activity.new(params[:activity]) @activity.user_id = self.current_user.id #why is this necessary??? but I guess rails can’t magically know what I mean by user??? can it?

if @activity.save @activity.users << User.find_by_id(self.current_user.id ) #habtm end

end

cheer

dion

Hi Dion,

I'm a little confused by your example. Why does Activity have a user_id on it if you have a HABTM relationship? There should be a join table named "activities_users" that has only two columns, "activity_id" and "user_id", and you shouldn't need a user_id column on Activity.

This line:

     @activity.users << User.find_by_id(self.current_user.id ) #habtm

should also probably just be

     @activity.users << current_user

to save yourself some database hits.

Regards,

-Seth

I have a habtm relationship between User and Activity

when I create a new Activity why do I have to manually set the foreign key user_id in the activity table???

You don't have to. The habtm relationship should set everything up automatically.

example

def create @activity = Activity.new(params[:activity]) @activity.user_id = self.current_user.id #why is this necessary??? but I guess rails can't magically know what I mean by user??? can it?

if @activity.save         @activity.users << User.find_by_id(self.current_user.id ) #habtm end

end

You're forgetting that @activity is just an AR object, not a database entry. In order to propagate the changes in the database you should call the save method:

@activity.users << User.find_by_id(self.current_user.id ) @activity.save

...

You're forgetting that @activity is just an AR object, not a database entry. In order to propagate the changes in the database you should call the save method:

@activity.users << User.find_by_id(self.current_user.id ) @activity.save

Actually you should try

@activity.users << current_user @activity.save

because you won't have to do an extra query.

@activity.users << current_user

does the trick, cheers

still curbing my old school thinking