Rails: create objects with `has_one` relation and skip validation

I encountered with this situation today;

I have `spree_user` object which can have one `bill_address` but bill address has one filed called `zipcode` field which is required and needs to be valid but I might not always have valid data for that field.

So needed to skip the validation for create method. Found that its not possible to skip validation using `create` method. 

Then I thought of using `save` method with `validate: false` but you know `save` method returns `boolean` object where I needed the `bill_address` object.

Yes I can save `bill_address` object how to relate that object with `spree_user`?
=> That’s not a solution I was looking for

Solution:

spree_user.build_bill_address(
    {
        firstname: raw_info.first_name,
        lastname: raw_info.last_name,
        address1: raw_info.payment_source.try(:billing_address) || '',
        address2: raw_info.payment_source.try(:billing_apt_or_suite) || '',
        city: raw_info.payment_source.try(:billing_city) || '',
        zipcode: '',
        phone: raw_info.phone,
        state_name: state.name,
        alternative_phone: nil,
        company: nil,
        state_id: state.id,
        country_id: country.id,

    }).save(validate: false)

This will skip validation as well as saves and related child object to parent.

Conclusion:

You can build or create object in relation to the parent object using `create_[associated_object]`  or `build_[associated_object]`

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s