【问题标题】:Ruby on Rails ---sql query for records of a specific userRuby on Rails --- sql 查询特定用户的记录
【发布时间】:2020-03-26 18:22:08
【问题描述】:

我是 ruby​​ on rails 的新手,如果有任何帮助,我将不胜感激。 这个应用程序旨在帮助学生获得他们的 sql 查询的结果。所以我期待学生输入sql。 我正在尝试为特定学生“从 uid

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.



  protect_from_forgery with: :exception
  before_action :ensure_login
  helper_method :logged_in?, :current_user

  def index

  end



  protected
    def ensure_login
      # Always go to login page unless session contains
      # reviewer_id
      redirect_to login_path unless session[:student_id]
    end

    def logged_in?
      session[:student_id] # nil is false
    end

    def current_user
      @current_user ||= Student.find(session[:student_id])
    end


end

在相应的控制器中,我写了这样的东西,试图只找到 current_user 的记录但它失败了(它给出了所有 uid

def findit

    #render json: { success: "It works", operator: params[:operator].inspect,condition: params[:condition].inspect,table: params[:table].inspect}

    @results = current_user.posts.find_by_sql(params[:sql])
    render json: { html: render_to_string(:template => 'all/findit') }
    #render json: { c: @columns}

  end

但posts_controller.rb 中的以下代码有效。它只有这个特定学生的记录。那么 findit 有什么问题呢?

 def index
    @posts = current_user.posts.all
  end

架构是:(还有一个会话模型)

ActiveRecord::Schema.define(version: 20200325201224) do

  create_table "posts", force: :cascade do |t|
    t.string  "title"
    t.text    "content"
    t.integer "uid"
    t.integer "student_id"
  end

  create_table "students", force: :cascade do |t|
    t.string   "name"
    t.string   "password_digest"
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
  end

  create_table "users", force: :cascade do |t|
    t.string  "name"
    t.integer "year"
    t.integer "uid"
    t.integer "student_id"
  end

end

非常感谢您的帮助!!!!

【问题讨论】:

  • 我真的不知道从哪里开始,因为有很多事情是关闭的。 1. 不要将动作放在 ApplicationController 中,因为它是所有控制器的超类,因此您要向所有控制器添加索引方法。 2. 你到底为什么在用户输入中使用find_by_sql?这是我见过的最大的 SQL 注入漏洞。
  • 这不是真的可以挽救的。你能描述一下这段代码应该解决的现实问题吗?
  • 感谢您的帮助,我刚刚编辑了更多信息。

标签: ruby-on-rails


【解决方案1】:

def current_user @current_user ||= Student.find(session[:student_id]) end

你让学生而不是用户是不正确的

这样做

def current_user @current_user ||= User.find(session[:student_id]) end

因为用户有 uid 并且没有关系来做类似 student.user.uid 的事情

要查找帖子然后执行此操作 Post.where(uid: @current_user.uid)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-18
  • 2012-06-10
相关资源
最近更新 更多