I'm new to ruby on rails and would appreciate any help. This application is meant to help students get the results of their sql query. So I'm expecting input of sql from the students. I'm trying to "select * from posts where uid <4" for a specific Student. That is , he can only see certain tuples with his student_id. And the application controller is as follows(where current user is the login information of this student):
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
In the corresponding controller, i wrote something like this ,trying to only find the current_user's records but it failed(it gives all the tuples with uid <4 no matter what's the 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
But the following code in posts_controller.rb works. It only has the records for this specific student. So what's wrong for findit?
def index
@posts = current_user.posts.all
end
The schema is:(And there's a session model too)
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
Thank you so much for helping!!!!
def current_user @current_user ||= Student.find(session[:student_id]) end
Thats incorrect your getting the student not the user
do this
def current_user @current_user ||= User.find(session[:student_id]) end
because the user has the uid and there are no relations to do something like student.user.uid
To find the post then do this Post.where(uid: @current_user.uid)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.