Variabili e nomi delle classi

Ciao raga

Volevo sottoporvi un quesito che purtroppo mi sta facendo rosicare una
cifra e contestualmente sentire un troglodita

Scenario: ho la mia classe Attachment che è in has_and_belongs_to_many con
2 o piu classi (nel mio caso Project e Visit)

Quando vado a definire il metodo “create” nell’attachments_controller,
mi porto dietro 2 parametri: referrer e foreignkey, cosi so che se vengo
da un progetto, l’attachment lo devo mettere a lui e se vengo da una
Visit stessa cosa

LA Domanda
è:
come posso sostituire il bruttissimo case - when e far interpretare la
variabile come se fosse il nome dell’oggetto? Praticamente mi servirebbe
l’equivalente del vecchio Eval

-------------------8<-----------------8<------------------8<--------------

def create
@foreignkey = params[:foreignkey]
@referrer = params[:referrer]
@oggetto = case @referrer
when ‘Project’ then Project.find(@foreignkey)
when ‘Visit’ then Visit.find(@foreignkey)
else nil
end

@attachment = Attachment.new(params[:attachment])
if @attachment.save
  @oggetto.attachments << @attachment
  flash[:notice] = 'Attachment was successfully created.'
  redirect_to :controller => Inflector.pluralize(@referrer), :action 

=> ‘home’, :id => @foreignkey
else
render :action => ‘new’
end
end

spero la risposta non sia troppo banale mi sentirei ancora peggio :smiley:

bella!
jeko

Stefano G. wrote:

Scenario: ho la mia classe Attachment che è in has_and_belongs_to_many con 2 o piu classi (nel mio caso Project e Visit)

def create
@foreignkey = params[:foreignkey]
@referrer = params[:referrer]
@oggetto = case @referrer
when ‘Project’ then Project.find(@foreignkey)
when ‘Visit’ then Visit.find(@foreignkey)
else nil
end
Potresti fare cosi:

@oggetto = Object.const_get( params[:referrer] ).new

Poi, se sei su Rails 1.1, ci sono le polymorphic associations che
consentono di associare ad un modello (e.g. Attachment) N diversi
modelli.

nel tuo caso devi avere in Attachment i campi referrer_id e
referrer_type poi:

class Project < ActiveRecord::Base
has_many :attachments, :as => :referrer
end

class Visit < ActiveRecord::Base
has_many :attachments, :as => :referrer
end

class Attachment < ActiveRecord::Base
belongs_to :referrer, :polymorphic => true
end

in questo modo puoi riferirti al referrer di un attachment come
attachment.referrer e questo sara’ un oggetto del tipo giusto.

per esempio se fai:

progetto = Project.new
attach = Attachment.new

puoi attaccare l’attach al progetto cosi:

attach.referrer = progetto

oppure

progetto.attachments << attach

senza doverti preoccupare di impostare il tipo, questo ti puo aiutare
soprattutto per le query.

ciao,
Luca M.

Web: http://spazidigitali.com
Email: mailto://[email protected]
Skype: callto://l.mearelli