mardi 12 avril 2016

Rails set child attribute values in Parent model

I have User model has_many relationship with Location model with reference key of user_id

Before saving the User model, I want to set the attribute values of Location model

class User < ActiveRecord::Base
attr_accessible :name :age, :gender, :location_enabled
has_many :location
accepts_nested_attributes_for :locationook, allow_destroy: true
before_save :update_book_attr

def update_book_attr
unless location_enabled
  # Here I have to set null for the child attributes if type = 1
  example
  {"0" => {"street" => "nil", "district" => "nil", "state" => "nil", "country" => "1", "type" => "1", "id" => "6"}, "1" => {"street" => "foo", "district" => "bar", "state" => "sample", "country" => "foo","type" => "2","id" => "7"}}
end
end

Location Model

class Location < ActiveRecord::Base
attr_accessible :user_id, :street, :district, :state, :country, :type
belongs_to :user
end

Aucun commentaire:

Enregistrer un commentaire