即使创建了具有参数的@user,也找不到没有ID的用户

时间:2019-07-05 06:58:28

标签: ruby-on-rails

我用Devise创建了一个Rails应用。

每个用户都应该能够答复填充模型Questionone的表格。 但是,我不断收到Couldn't find User without an ID

我做了什么: rails generate scaffold Questionone first_question:text second_question:text user:references

在我的 User.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  has_many :questionones
end

在我的 Questionone.rb 中,我有:

class Questionone < ApplicationRecord
  belongs_to :user
end

在我的 questiones_controllers

before_action :set_questionone, only: [:show, :edit, :update, :destroy]

  def new
    @questionone = Questionone.new
    @user = User.find(params[:user_id])
    #If I use @user = current_user.id it works, but not sure if is right way
  end

  def create
    @questionone = Questionone.new(questionone_params)
    @questionone.user = User.find(params[:user_id])
    @questionone.save
  end
  private
    # Use callbacks to share common setup or constraints between actions.
    def set_questionone
      @questionone = Questionone.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def questionone_params
      params.require(:questionone).permit(:user_id, :first_question, :second_question)
    end
end

如果我使用raise,它告诉我@usernil

如果我使用@user = current_user.id ,它会起作用,但是我不确定这是正确的方法

1 个答案:

答案 0 :(得分:2)

那里有一些错误的逻辑。答案是这样:

  def new
    @questionone = Questionone.new
    @user = current_user
  end

  def create
    @questionone = Questionone.new(questionone_params)
    @questionone.user = current_user
    @questionone.save
  end

此外,您不是要记住Questionone(?怪异的名称:D),您应该这样做:

def set_questionone
  @questionone ||= Questionone.find(params[:id])
end

更长的答案: 我认为用户范围应限于当前登录的用户范围。如果正确的话,那么您将引入一个严重的安全问题,任何人都可以通过在参数中按下user_id来提出问题。

完全删除user_id参数,并使用current_user变量。