Creating association with .build and working aroun

2019-09-11 13:45发布

问题:

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

回答1:

I didn't understand very much your question. Hope this helps:

@item = current_owner.items.build(params[:item])
if @item.valid?
  # item is valid and ready to save to DB
else
  # item is not valid.
end


回答2:

You have password validations in your model which requires the presence of password. What you can do is as follow

@item = current_owner.items.build(params[:item])
if @item.valid?
   @item.save
  # do stuff what you want
else
  # item is not valid.
end

Hope it would help