私は三つのモデルを持っています。 投稿とコメントをするために多態的な関連付けを使用しています (ユーザーは+1と-1を投票できます)投稿、コメント、ユーザー、投票モデルがすべて設定されています。ユーザーを投票できるようにするにはどうすればいいですか? <strong>ポスト</strong>、<strong>コメント</strong>、<strong>ユーザー</strong>と<strong>投票</strong>:
たびにユーザーがポストやコメントを投票し、そのidは投票のuser_id
外部キーに格納されます(ポストとコメントのIDは、同様にvotable_id
とvotable_type
外部キーに格納する必要があります)。
post.rb:
class Post < ActiveRecord::Base
attr_accessible :title, :content
belongs_to :user
has_many :comments, :dependent => :destroy
has_many :votes, :as => :votable, :dependent => :destroy
end
comment.rb:
class Comment < ActiveRecord::Base
attr_accessible :content, :user_id
belongs_to :post, :counter_cache => true
belongs_to :user
has_many :votes, :as => :votable, :dependent => :destroy
end
user.rb(考案の一部省略):
class User < ActiveRecord::Base
has_many :posts, :dependent => :destroy
has_many :comments, :dependent => :destroy
has_many :votes
end
vote.rb:私は「
- :私は2つの質問がある
create_table "comments", :force => true do |t| t.text "content" t.integer "post_id" t.integer "user_id" end add_index "comments", ["post_id", "user_id"], :name => "index_comments_on_micropost_id_and_user_id" create_table "posts", :force => true do |t| t.string "content" t.integer "user_id" t.string "title" t.integer "comments_count", :default => 0, :null => false end create_table "users", :force => true do |t| t.string "email", :default => "", :null => false t.string "username" end add_index "users", ["email"], :name => "index_users_on_email", :unique => true add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true create_table "votes", :force => true do |t| t.integer "votable_id" t.string "votable_type" t.integer "user_id" t.integer "polarity" // (+1 or -1) t.integer "total" end
:
class Vote < ActiveRecord::Base belongs_to :votable, :polymorphic => true belongs_to :user before_create :update_total protected // Update the value of total each time a vote is created def update_total self.total ||= 0 self.total += self.polarity end end
schema.rbは(関連部分のみ、のcreated_atのような省略ものを含みます)
total
は、posts
またはvotes
テーブルの列である必要があります。 - 端末での投票方法(例:
Vote.create(polarity => 1
)を知っています。しかし、それ以外にも、実際にDeviseに投稿やコメント(端末内)を投票させる方法を知りたいのですが。
上記の問題のお手伝いをお待ちしております。