ruby on rails - Associating a new object with an existing object with has_many through -
i have 2 classes users , projects. user can own many projects , project can owned many users. however, project must have @ least 1 user while user not necessary have have project.
this have:
class project < activerecord::base attr_accessible :prj_id, :name has_many :ownerships, foreign_key: "project_id", dependent: :destroy has_many :users, through: :ownerships end class user < activerecord::base attr_accessible :first_name, :last_name, :email, :password, :password_confirmation has_many :ownerships, foreign_key: "user_id", dependent: :destroy has_many :projects, through: :ownerships validates :first_name, presence: true, length: { maximum: 25 } validates :last_name, presence: true, length: { maximum: 25 } valid_email_regex = /\a[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence: true, format: { with: valid_email_regex }, uniqueness: { case_sensitive: false } validates :password, presence: true, length: { minimum: 6 } validates :password_confirmation, presence: true end class ownership < activerecord::base attr_accessible :project_id belongs_to :user, class_name: "user" belongs_to :project, class_name: "project" validates :user_id, presence: true validates :project_id, presence: true end
thus, user must exist first before can create project. having trouble is when try create new project , append users new project, not allow me save because user exists in user table. more specifically, in rails console:
>> prj = project.new(prj_id: 'hello', name: 'hello') >> usr = user.find_by_id(1) >> prj.users<<usr >> prj.save
the prj.save line fails giving message:
(0.1ms) savepoint active_record_1 user exists (0.1ms) select 1 one "users" (lower("users"."email") = lower('example@example.com') , "users"."id" != 1) limit 1 (0.1ms) rollback savepoint active_record_1 => false
is there way associate new project existing user(s), creating new entry in both project table , ownership table while checking if user exists in user table (and not try create new user)? thanks!
your project's ownership record invalid because requires presence of project_id
, nil
new project. you'll either need create project first or change validation in ownership
model.
you can see inspecting errors object of models involved:
> prj.errors.full_messages => ["ownerships invalid"] > prj.ownerships.first.errors.full_messages => ["project can't blank"]
Comments
Post a Comment