繁体   English   中英

Ruby on Rails ---sql 查询特定用户的记录

[英]Ruby on Rails ---sql query for records of a specific user

我是 ruby​​ on rails 的新手,希望得到任何帮助。 此应用程序旨在帮助学生获取 sql 查询的结果。 所以我期待学生的 sql 输入。 我正在尝试为特定学生“从 uid <4 的帖子中选择 *”。 也就是说,他只能看到某些带有他的 student_id 的元组。 应用控制器如下(当前用户是该学生的登录信息):

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 <4 的所有元组,无论 student_id 是什么):

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

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM