Using Rails 3.2.9
I'm attempting to build a association using .build instead of .create but getting a password validation error that I can't seem to find a workaround.
Review below:
The way I understand to save a item with a association that is built using .build you actually have to do the save in this case on the owner. If you do a save on the @item it just creates the item and not the association(meaning it doesn't save to the DB until current_owner.save). when i do a save on the owner i hit a error due to password not meeting the validation requirements. Is there a way to bypass the validation when I do a save, due i need to implement a different solution for password, or just stop complaining and use .create instead of .build.
The below gives a password does not meet validation error
@item = current_owner.items.build(params[:item])
if current_owner.save
Do some other work with item
end
I guess i could do the following(for some reason it seems dirty to me maybe not. Thoughts?)
@item = current_owner.items.create(params[:item])
if !@item.nil?
Do some other work with item
end
Table Setup: owners:
- id
- name
- encrypted_password
- salt
items:
- id
- name
items_owners:
- owner_id
- item_id
Models:
class Item < ActiveRecord::Base
attr_accessible :description, :name, :owner_ids
has_many :items_owner
has_many :owners, :through => :items_owner
end
class Owner < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :password, password_confirmation
has_many :items_owner
has_many :items, :through => :items_owner
before_save :encrypt_password
validates :password, :presence => true,
:confirmation => true,
:length => { :within => 6..40 }
end
class ItemsOwner < ActiveRecord::Base
attr_accessible :owner_id, :item_id
belongs_to :item
belongs_to :owner
end