Domanda

Ho un modello che, quando si crea un'istanza di un oggetto, crea anche un altro oggetto con lo stesso user id.

class Foo > ActiveRecord::Base

after_create: create_bar

private

def create_bar
  Bar.create(:user_id => user_id #and other attributes)
end

end

In Bar.rb ho attr_protected per proteggerlo dagli hacker.

class Bar > ActiveRecord::Base
  attr_protected :user_id, :created_at, :updated_at
end

così com'è ora non riesco a creare un nuovo oggetto bar senza né disabilitare il attr_protected o aventi dell'oggetto Bar id_utente andare in bianco ...

Come posso lasciare che l'oggetto barra di accettare il:? Attributo user_id da foo senza perdere la protezione da attr_protected

È stato utile?

Soluzione

Prova a fare:

def create_bar
  bar = Bar.build(... other params ...)
  bar.user_id = user_id
  bar.save!
end

Altri suggerimenti

Quando si chiama new, create o find_or_create_by (e tutti gli altri che finiscono new chiamare) è possibile passare un'opzione aggiuntiva, without_protection: true.

http: //api.rubyonrails. org / v3.2.22 / classes / ActiveRecord / Base.html # metodo-c-nuova

attr_protected filtra gli attributi nel metodo attributes= wich è chiamato a new. È possibile risolvere il problema con:

def create_bar
  returning Bar.new( other attributes ) do |bar|
    bar.user_id = user_id
    bar.save!
  end
end
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top