开发者

passing a parameter from an other model on ruby

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 pas开发者_Python百科s 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


@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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜