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.
精彩评论