views:

28

answers:

2

I'm very newbie in ruby and need your help.

I must save a "Topic" and make it like this :

@topic = Topic.new(params[:topic])

But I would like to pass an other information to this topic. It has a field "community_id" that link it to a community. The logged user has this information on his table.

How can I pass the "community_id" from the logged user to the "community_id" of the "topic" created ?

thx for your help

+3  A: 
@topic = Topic.new(params[:topic])
@topic.community = @user.community
@topic.save

This will create a new Topic object with the hash parameters you pass it. And will define it's community to the user's one.

Damien MATHIEU
+1  A: 

There are three methods: (I made a guess on how you are retrieving the community_id from the user, this won't be exact)

@topic = Topic.new(params[:topic])
@topic.community = @user.community

or

@topic = Topic.new(params[:topic].merge(:community_id => @user.community_id))

or

@topic = @user.community.topics.new(params[:topic])

(None of this code is tested)

The second assumes that community_id is attr_accessible.

The third is probably the cleaner way to do it, and it is how I do it. The second is nice if the model belongs to more than one model, though.

mathepic