0

I am having trouble saving objects to their corresponding tables.

Model Customer. I want to make sure it has an associated valid Account:

has_one :account, dependent: :destroy
validates_presence_of :account
validates_associated :account

Model Account belongs to Customer, so I want to enforce customer_id is present:

belongs_to :customer
validates :customer_id, presence: true

Now, my question is: Which order should I save these objects? Are these validations somewhat incompatible?

Because, if I try to save Customer first, it won't be possible, I will get

myCustomer.save.errors.messages
{:account=>["can't be blank"]}

Obviously, since I stated

validates_presence_of :account

in the model.

But if I try to save Account first, wait! I can't save it either! I have

validates :customer_id, presence: true

in my Account model and I haven't saved any customer yet !

So I have also tried to just initialize the Account:

acc = Account.new(acc_attr: foo, acc_attr2: bar)

and then try to set it to Customer like this

Customer.account = acc

But then again, customer won't save since acc is not valid, (since it doesn't have a customer_id and I have validates_associated :account in the Customer model)

So, will I have to give up on one validation in either model? Is there a workaround for this?

Thanks!

Vital V
  • 235
  • 1
  • 4
  • 15

1 Answers1

0

You can add this into your model:

attr_accessible: :customer_id

And add to GemFile:

gem 'devise', '3.0.0.rc' 
gem 'protected_attributes'
  • run in terminal: $ bundle install
  • reset server

You should check in your controller:

params.require(:account).permit(:customer_id)
yagi_chan
  • 13
  • 6
  • What do I need devise for? Also, I have no controllers yet. I just want to save those objects. – Vital V Aug 28 '13 at 08:39
  • Use `attr_accessible: :customer_id` to access database. And devise is used for attr_accessible. Controller is a option, if you have no any controller for your model, you don't need check in controller. – yagi_chan Aug 28 '13 at 08:49
  • [Rails 4 uses strong parameters](http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html). `attr_accessible` has been deprecated, as is noted [here](http://apidock.com/rails/ActiveModel/MassAssignmentSecurity/ClassMethods/attr_accessible). [This SO answer](http://stackoverflow.com/a/17371364) has a good description of how strong parameters work in place of `attr_accessible`. – Bart Riordan May 11 '15 at 15:39