Полиморфная ассоциация не сохраняет ClassName (без STI), какие-либо подсказки? - PullRequest
1 голос
/ 03 апреля 2009

У меня есть две модели, одна называется Notes, а другая - Comments. Комментарии могут быть связаны со многими другими моделями, поэтому я использую полиморфную ассоциацию. В schema.rb это выглядит так:

  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

Когда я хочу сохранить комментарий к заметке, кажется, что все работает:

    # 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

Странно, что в таблице комментариев он сохраняет commentable_type = 0, а не = "Note", как и должно быть Он по-прежнему находит комментарии, если я ввожу @ 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

Я не понимаю этого поведения. У вас есть идеи?

1 Ответ

2 голосов
/ 03 апреля 2009

ты очень близко! Просто измените столбец commentable_type на строку, а не на целое число, и оно должно быть заполнено правильно (конечно, при условии, что объявления модели верны). Для справки я приведу пример того, как это должно быть настроено:

# Comment model
class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
end

# Other models which can contain comments
class AnotherModel < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

class YetAnotherModel < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

Также для всех, кто находится в такой ситуации, есть миграция, которая внесет изменения:

class ChangeCommentableTypeToString < ActiveRecord::Migration
  def self.up
    change_column(:comments, :commentable_type, :string)
  end

  def self.down
    change_column(:comments, :commentable_type, :integer)
  end
end
...