首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Rails 4中设计用户评审/评级系统

在Rails 4中设计用户评审/评级系统
EN

Stack Overflow用户
提问于 2014-03-21 08:00:24
回答 2查看 1.6K关注 0票数 0

我试图为rails中的用户创建一个审查系统。我希望一个用户能够在他们的配置文件页面中对另一个用户进行评分。我尝试过几种不同的方法,但我对rails相当陌生,还没有做到这一点。

现在,我有默认的设计视图,但没有用户配置文件页面。我希望用户审查另一个用户的5个左右不同的问题。

任何帮助都将不胜感激!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-03-21 08:40:38

为此,您可以使用称为has_many through关联:basics.html#the-has-many-through-association的关联。

你的模特应该是这样的“

代码语言:javascript
复制
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

你的迁徙:

代码语言:javascript
复制
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
票数 4
EN

Stack Overflow用户

发布于 2014-03-21 09:21:53

Oxynum -伟大的概念!在添加模型和应用迁移之后,从模板开始。对于您来说,起点是users_controller.rb。很可能,你已经在UsersController里面有了一个“秀”动作。此操作可供经过身份验证的用户使用。将此操作修改为类似于:

代码语言:javascript
复制
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

在路线上增加:

代码语言:javascript
复制
get 'users/update_rating/:value' => 'user#update_rating'

启动rails服务器,登录,并尝试直接更改评级:

代码语言:javascript
复制
  http://localhost:3000/users/update_rating/up
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22553235

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档