开发者

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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜