J'ai deux modèles, un appelé Notes et un appelé Commentaires. Les commentaires peuvent être associés à de nombreux autres modèles, donc j'utilise une association polymorphe. Dans le schema.rb il ressemble à ceci:L'association polymorphique n'enregistre pas le nom de classe (sans STI), aucun indice?
create_table "comments", :force => true do |t|
t.text "body"
t.integer "user_id"
t.integer "commentable_id"
t.integer "commentable_type"
t.datetime "created_at"
t.datetime "updated_at" end
Quand je veux sauver un commentaire à tout note semble fonctionner:
# POST /comments
# POST /comments.xml
def create
@comment = Comment.new(params[:comment])
@comment.user = current_user
respond_to do |format|
if @comment.save
process_file_uploads
flash[:notice] = 'Comment was successfully created.'
if !params[:note_id].nil?
@note = Note.find(params[:note_id])
debugger
@note.comments << @comment
format.html { redirect_to(@note) }
format.xml { render :xml => @note, :status => :created, :location => @note }
else
format.html { redirect_to(@comment) }
format.xml { render :xml => @comment, :status => :created, :location => @comment }
end
else
format.html { render :action => "new" }
format.xml { render :xml => @comment.errors, :status => :unprocessable_entity }
end
end
end
La chose étrange est que, dans la table de commentaire enregistre commentable_type = 0 et non = "Note" comme il se doit. Il trouve toujours les commentaires si j'entre @ note.comments.
Comment Update (0.4ms) UPDATE `comments` SET `commentable_type` = 0, `commentable_id` = 11, `updated_at` = '2009-04-03 10:55:50' WHERE `id` = 5
Je ne comprends pas ce comportement. As tu des idées?
OMG! C'est tellement embarrassant ... Je ne peux pas le croire. Parfois, on cherche les solutions complexes et les pensées de base manquent. Doh! Merci! –
Ça nous arrive à tous! Je viens d'ajouter une migration au cas où cela vous aiderait ou n'importe qui. –