Posted by
ihower
on
July 19, 2010
Use model association to avoid assigning reference in controller.
Bad Smell
class PostsController < ApplicationController
def create
@post = Post.new(params[:post])
@post.user_id = current_user.id
@post.save
end
end
In this example, user_id is assigned to @post explicitly. It's not too big problem, but we can save this line by using model association.
Refactor
class PostsController < ApplicationController
def create
@post = current_user.posts.build(params[:post])
@post.save
end
end
class User < ActiveRecord::Base
has_many :posts
end
We define the association that user has many posts, then we can just use current_user.posts.build or current_user.posts.create to generate a post, and the current_user's id is assigned to the user_id of the post automatically by activerecord.

Comments
@post = Post.new(params[:post]):Thanks
For example, let's say you have models Article, User and Group.
and ArticlesController:
Is there a cleaner way ?
@article=current_user.articles_with_subdomain(current_subdomain).build(param[:article])Might seem cumbersome on a first sight. Anyway you should see Advanced Queries in Rails 3. IMHO nice way to build such models.
[code]
@article = current_user.build(params[:article], :subdomain_id => current_subdomain.id)
[/code]
But we have a mass assignment security problem with this pattern. Because you can pass pos[user_id] as param. So, my solutions is: