activerecord - Rails updating column rows for has_one relationship -
i have added iconfolio
character model. each character has_one :iconfolio
.
character.rb
has_one :iconfolio, dependent: :destroy accepts_nested_attributes_for :iconfolio before_validation self.create_iconfolio unless iconfolio end
here migration file:
class createiconfolios < activerecord::migration def change create_table :iconfolios |t| t.integer :character_id t.string :icon_url t.timestamps null: false end add_index :iconfolios, :character_id end end
the iconfolio class:
iconfolio.rb
class iconfolio < activerecord::base belongs_to :character validates :character_id, presence: true before_create self.icon_url = '/assets/icon1.png' end end
firstly, how ensure iconfolio
has been created each character
?
secondly, how update rows in character_id
column? character_id
value different every iconfolio
record. updating icon_url
column can done in console:
iconfolio.all.update_all(person_normal_icon_url: '/assets/icon1.png')
the easiest way create default template iconfolio , update_all
character records did iconfolio. if database isn't large can iterate through character.all
, assign them iconfolio. advised instantiate object per row , more time consuming update_all. benefit of instantiating them not bypass validations. write block in console iterates through each record , finds or creates iconfolio per character like:
character.all.find_each |char| if char.iconfolio.blank? iconfolio.create(character_id: char.id, whatever_other_params: put_here) end end
then make after_create in character model creates , assigns iconfolio future new characters. like:
after_create :make_an_iconfolio def make_an_iconfolio iconfolio.create(character_id: self.id, other params here) end
as sidenote, rails way add relationship in create_table migration is:
def change create_table :iconfolios |t| t.belongs_to :character, index: true
this makes more clear , others it's relationship , saves line of code indexing.
Comments
Post a Comment