RoR3 Devise - Projects per Users
I am working on very simple application for managing user projects. There are two models, User and Project. User should view only projects they created. So, model Project has user_id column for linking with User. Models:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, :rememberable, :validatable
has_many :projects, :dependent => :destroy
attr_accessible :email, :password, :password_confirmation, :remember_me
end
class Project < ActiveRecord::Base
belongs_to :user
end
When user creates new project, user id should be au开发者_如何学Ctomatically added to user_id column. This is accomplished in Project controller under create action:
def create
params[:project][:user_id] = current_user.id
@project = Project.new(params[:project])
#...
This works when I add user_id to params[:project] but I have a feeling this is not a proper way to do is. Or is it?
def create
@project = current_user.projects.build(params[:project])
#...
http://guides.rubyonrails.org/association_basics.html#has_many_collection_build
精彩评论