我正在尝试在rails中为用户创建一个评论系统。我希望一个用户能够在设备的个人资料页面上为另一个用户评分。我已经尝试了一些不同的方法,但我对rails很新,但却无法实现这一目标。
现在我有默认设计视图,但没有用户个人资料页面。我希望用户在5个左右的不同问题上审核另一个用户。
非常感谢任何帮助!
答案 0 :(得分:4)
为此,您可以使用名为has_many through
关联的关联:
http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
你的模型应该看起来像那样“
class User < ActiveRecord::Base
has_many :rates
has_many :rated_users, through: :rates, class_name: "User", foreign_key: :rated_user_id # The users this user has rated
has_many :rated_by_users, through: :rates, class_name: "User", foreign_key: :rating_user_id # The users that have rated this client
end
class Rates < ActiveRecord::Base
belongs_to :rating_user, class_name: "User"
belongs_to :rated_user, class_name: "User"
end
您的迁移:
class createRates < ActiveRecord::Migration
def change
create_table :changes do |t|
t.belongs_to :rated_user
t.belongs_to :rating_user
t.integer :value
t.timestamps
end
end
end
答案 1 :(得分:0)
Oxynum - 很棒的概念!添加模型并应用迁移后,从模板开始。您的起点是users_controller.rb。也许,你已经在UsersController中有一个'show'动作。此操作适用于经过身份验证的用户。 将此操作修改为如:
class UsersController < ApplicationController
before_filter :authenticate_user!
before_filter :load_ratable, :only => [:show, :update_rating]
def show
# Renders app/views/users/show.html.erb with user profile and rate controls
end
def update_rating
my_rate_value = params[:value] == 'up' ? +1 : -1
if @rated_by_me.blank?
Rate.create(rated_user: @userProfile, rating_user: @user, value: my_rate_value)
flash[:notice] = "You rated #{@userProfile.name}: #{params[:value]}"
else
flash[:notice] = "You already rated #{@userProfile.name}"
end
render action: 'show'
end
protected:
def load_ratable
@userProfile = User.find(params[:id]) # - is a viewed profile.
@user = current_user # - is you
@rated_by_me = Rate.where(rated_user: @userProfile, rating_user: @user)
end
end
添加到路线:
get 'users/update_rating/:value' => 'user#update_rating'
启动rails服务器,登录,然后尝试直接更改评级:
http://localhost:3000/users/update_rating/up