Reputation: 814
I have a models like Routine and RoutineContent for localization
in Routine.rb
Class Routine < ActiveRecord::Base
has_many :routine_contents, dependent: :destroy
accepts_nested_attributes_for :routine_contents, reject_if: proc {|attributes| attributes['title'].empty?}
end
and in RoutinesContent
class RoutineContent < ActiveRecord::Base
belongs_to :routine
validates_presence_of :title
end
In the new Routine action I puts on RoutineConten fields for languages. If title in one object is emty then this object will rejected.
When I go to edit action, I do this
def set_routine_contents
contents = @routine.routine_contents.group_by {|content| content.lang}
if contents['ru'].nil?
@routine.routine_contents << RoutineContent.new(lang: 'ru')
end
if contents['en'].nil?
@routine.routine_contents << RoutineContent.new(lang: 'en')
end
end
end after this Rails INSERT INTO emty object in table, why? How I can disable it? Thanks
Upvotes: 1
Views: 81
Reputation: 814
Solution
def set_routine_contents
contents = @routine.routine_contents.group_by {|content| content.lang}
if contents['ru'].nil?
@routine.routine_contents.build(lang: 'ru')
end
if contents['en'].nil?
@routine.routine_contents.build(lang: 'en')
end
end
Use the build method. Add to Array via << it was bad idea
Upvotes: 1
Reputation: 3616
has_many
association implemented with foreign key in routine_id
in routine_contents
table.
So adding new RoutineContent to your Routine requires determined primary key in Routine to write to routine_id
, and causes Routine to save if not saved yet.
Upvotes: 0