用户信息未存储到适当的用户

时间:2016-08-01 05:01:35

标签: ruby-on-rails model-view-controller associations

在我的用户控制器中,我有以下方法

def show
  @user = User.find(params[:id])
  if current_user.id == params[:id] # im not sure if this is right
    @answer = Answer.new
  else
    @answer = Answer.find(params[:id])
  end
end

其中

class User 
  has_many :answers
end

class Answer 
  belongs_to :user
end

当我通过登录用户(B)打开另一个用户(A)时,我希望A的测验问题(通过has_one关联也属于用户)通过B获得答案。

按原样,如果B回答A的问题,然后我用A登录,他们将得到原始B到A的相同答案。

如果有帮助,在我的Answers控制器中我有以下方法。

def create
  @answer = current_user.answers.build(answer_params)
  if @answer.save
    flash[:success] = "Updated"
    redirect_to '/'
  else
    render 'new'
  end
end

def update
  respond_to do |format|
    @answer = Answer.find(params[:id])
    if @answer.update(answer_params)
      format.html { redirect_to '/', notice: 'Answers were successfully updated.' }
      format.json { render :show, status: :ok, location: @answer }
    else
      format.html { render :edit }
      format.json { render json: @answer.errors, status: :unprocessable_entity }
    end
  end
end


def answer_params
  params.require(:answer).permit(:r1, :r2, :r3, :r4, :r5)
end

我也有迁移

class AddUserIdToAnswers < ActiveRecord::Migration
  def change
    add_column :answers, :user_id, :integer
  end
end

编辑: 测验控制器(belongs_to User,User has_one:quiz)

class QuizzesController < ApplicationController

def edit
@quiz = Quiz.find(params:[id])
end

def create
@quiz = current_user.build_quiz(quiz_params)
if @quiz.save
  flash[:success] = "Updated"
  redirect_to '/'
else
  render 'new'
end
end

def update
respond_to do |format|
@quiz = Quiz.find(params[:id])
  if @quiz.update(quiz_params)
    format.html { redirect_to '/', notice: 'Quiz was successfully updated.' }
    format.json { render :show, status: :ok, location: @quiz }
  else
    format.html { render :edit }
    format.json { render json: @quiz.errors, status: :unprocessable_entity }
  end
  end
  end


  def quiz_params
 params.require(:quiz).permit(:q1, :q2, :q3, :q4, :q5)
  end

  def show
 @quizzes = Quiz.all
  end

 end

和我的Routes.rb

Rails.application.routes.draw do
 mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
 devise_for :users

 root to: 'welcome#landing'
 resources :users, :quizzes, :answers

2 个答案:

答案 0 :(得分:0)

我没有经历过各个方面。但是你的节目动作中有一个问题。

if current_user.id == params[:id] # im not sure if this is right

有了这个,你就不会得到新的表格。因为params[:id]类型是字符串而current_user.id类型是整数。所以它总会返回false。

尝试改变:

if current_user.id == params[:id].to_i

或直接比较用户对象

if current_user == @user

答案 1 :(得分:0)

尝试我的建议helpisgood

def show
 @user = User.find(params[:id])

 if current_user == @user
    @answer = Answer.new
 else
    @answer = Answer.find_by(user_id: @user.id)
 end
end