Nested attributes and adding attributes through the controller?

Since this question is hard to describe, the best headline I could come up with, so here is some code.

Given the three models of Parent, Child && Grandson.

Parent <  ActiveRecord::Base
  has_many :children
  has_many :grandchildren
  accepts_nested_attributes_for :child
end

Child <  ActiveRecord::Base
  belongs_to :parent
  has_many :kids, :as => :grandchildren #this is just an example
  accepts_nested_attributes_for :grandchild
end

Grandchild <  ActiveRecord::Base
  belongs_to :parent
  belongs_to :child
end

I want to add current_user.id to both the child record and the Grandchild record that is created during Parent # new. I used hidden fields because I could not find a good way to add them.

Can someone help by creating a callback to add current_user.id to create? In any case, I never managed to get this in the model, but you are smart.

Thoughts?

+3
source share
2 answers

, -, has_many :through ( ) . . " " API- ActiveRecord.

, , , , . , - ( ):

class Parent
  # ...somewhere at the top...
  before_create :set_current_user_on_descendants

  # ...somewhere in the main class body...
  # (I assume parent['current_user'] is passed in as a typical 
  # parameter, and thus self.current_user is already set.)
  def set_current_user_on_descendants
    children.each { |c| c.current_user = self.current_user }
    grandchildren.each { |gc| gc.current_user = self.current_user }
  end
end

, -. "", + , , , ( DRYness, , ). , current_user, before_save before_create - API ActiveRecord.

+5

, save!

class Parent < ActiveRecord::Base
   def save! 
      children.each { |c| c.current_user = @current_user }
      grandchildren.each { |gc| gc.current_user = @current_user }

      super
   end
end

. , ...

0

Source: https://habr.com/ru/post/1726820/


All Articles