Rails表单从不同的控制器更新属性

时间:2016-06-21 03:30:47

标签: ruby-on-rails ruby

我有一个带有演示和评级的应用程序。基本思想是每个用户都可以对演示进行评分,他们可以更新评级。但是,我遇到了很多错误:

  1. 更新演示的评级
  2. 创建表单以更新评级
  3. 演示控制器

    def show
        @demo = Demo.find(params[:id])
        @user = User.find(@demo.user_id)
        @topic = Subject.find(@demo.subject_id)
        if repeat_reviewer?(current_user)
            @rating = Rating.create(reviewer: current_user, reviewed: @demo)
        else
            @rating = Rating.where(reviewer: current_user, reviewed: @demo)
        end
    end
    
    ....
    
    def repeat_reviewer?(user)
        @demo = Demo.find(params[:id])
        return false unless user == User.where(reviewed: @demo)
    end
    
    def update_average_rating
        @value = 0
        self.ratings.each do |r|
            @rating += @rating.value 
        end
        @total = self.ratings.size
    
        update_attributes(rating_average: @value.to_f / @total.to_f)
    end
    

    评级控制器

    before_action :require_user, only: [:create, :update]
    after_action :update_demo_rating
    
    def create
        @rating = Rating.create(rating_params)
        if @rating.save 
            redirect_back_or
        end
    end
    
    def update
      @rating = Rating.where(reviewer: current_user)
      if @rating.update_attributes(rating_params)
        redirect_back_or
      end
    end
    
    private
    
    def rating_params
        params.require(:rating).permit(:value, :reviewer_id, :reviewed_id)
    end
    
    def update_demo_rating
        @rating = Rating.find(params[:id])
        @demo = @rating.reviewed
        @demo.update_average_rating
    end
    

    演示展示视图

    <%= form_for @rating, url: ratings_path(@rating), method: :put do |f| %>
    <%= options_for_select([[5,5],[3,3],[1,1]], 1) %>
    <%= f.submit %>
    

    我在生成表单时遇到错误,更新了正确的属性,还找到了与演示和用户相关的评级。

0 个答案:

没有答案