2009-04-03 3 views
1

私は2つのモデルを持っています.1つはノーツと呼ばれ、もうひとつはコメントと呼ばれます。コメントは他の多くのモデルに関連付けることができるので、多態性の関連付けを使用します。私はノートのすべてにコメントを保存したいときに動作しているようですPolymorphic AssociationはClassName(STIなし)を保存しませんが、ヒントはありますか?

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 

奇妙なことは、コメントテーブルにそれが保存していることであるschema.rbでは、このようになりますcommentable_type = 0、not = "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 

この動作はわかりません。あなたはなにか考えはありますか?

答えて

2

あなたは非常に近いです! 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 
+0

OMG!それはとても恥ずかしいです....私はそれを信じることができません。時々、複雑な解決策を探して、基本的な考え方を逃してしまいます。ドー! ありがとう! –

+0

それは私たちすべてに起こります!あなたや他の人に役立つ場合は、移行を追加しました。 –

関連する問題