Skip to content

Instantly share code, notes, and snippets.

@ceritium
Created September 26, 2011 17:03
Show Gist options
  • Save ceritium/1242744 to your computer and use it in GitHub Desktop.
Save ceritium/1242744 to your computer and use it in GitHub Desktop.
class Project
include Mongoid::Document
include Mongoid::Timestamps
embeds_many :histories
has_many :invitations
field :name, type: String
validates_presence_of :name
has_and_belongs_to_many :users
end
# work
def create
@project = Project.new(params[:project])
if @project.save
@project.users << current_user
redirect_to project_path(@project), :notice => 'Project created'
else
render 'new'
end
end
# no work
def create
@project = current_user.projects.build(params[:project])
if @project.save
redirect_to project_path(@project), :notice => 'Project created'
else
render 'new'
end
end
class User
include Mongoid::Document
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
field :name
validates_presence_of :name
validates_uniqueness_of :name, :email, :case_sensitive => false
attr_accessible :name, :email, :password, :password_confirmation, :remember_me
has_and_belongs_to_many :projects
end
@werelax
Copy link

werelax commented Sep 26, 2011

@Nerian But if for some reason @project.save works but current_user.save blows up, you will end with a corrupted relationship. I think that is safer to go with something like

def create
  @project = current_user.create!(params[:project])
  redirect_to @project, :notice => 'Project created'
rescue Mongoid::Errors::Validations
  # You can check for sanity here
  render 'new'
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment