我试图为rails中的用户创建一个审查系统。我希望一个用户能够在他们的配置文件页面中对另一个用户进行评分。我尝试过几种不同的方法,但我对rails相当陌生,还没有做到这一点。
现在,我有默认的设计视图,但没有用户配置文件页面。我希望用户审查另一个用户的5个左右不同的问题。
任何帮助都将不胜感激!
发布于 2014-03-21 08:40:38
为此,您可以使用称为has_many through关联: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发布于 2014-03-21 09:21:53
Oxynum -伟大的概念!在添加模型和应用迁移之后,从模板开始。对于您来说,起点是users_controller.rb。很可能,你已经在UsersController里面有了一个“秀”动作。此操作可供经过身份验证的用户使用。将此操作修改为类似于:
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/uphttps://stackoverflow.com/questions/22553235
复制相似问题