Created
September 26, 2011 17:03
-
-
Save ceritium/1242744 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
@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
Exactly,
project
is not being marked asdirty
and thus is not saved automatically. As to why, I don't know :)This should work: