Rails:用孙子(协会)查询父母

时间:2016-09-08 06:01:17

标签: ruby-on-rails ruby associations ruby-on-rails-5

class User < ActiveRecord::Base
  has_many :posts
end

class Question < ActiveRecord::Base
  belongs_to :user
  has_many :answers
end

class Answer < ActiveRecord::Base
  belongs_to :question
end

如何使用Rails:

1.使用users返回所有questions?例如

@users_with_questions = User.joins(:question).where.not(question: { id: nil })

2.使用users返回所有answers

3 个答案:

答案 0 :(得分:1)

1.回答所有用户的问题?

@users_with_questions = User.includes(:question).where.not(:question => {id: nil})

2.使用答案返回所有用户?

@users_with_answers = User.includes(question: :answer).where.not(:answer => {id: nil})

答案 1 :(得分:0)

试试这个:

<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
error_reporting(1);

require_once(APPPATH . 'libraries/dropbox/vendor/autoload.php');

use \Dropbox as dbx;

class Knowledge extends CI_Controller
{
    public $appInfoFile;
    public $requestPath; **




    public function __construct()
    {
        parent::__construct();
        $this->load->library('session');

        $this->load->helper('form');
        $this->load->helper('url');
        $this->load->database();
        $this->load->library('form_validation');

        //load the models
        $this->load->model('knowledge_model');

        //$this->load->helper('messages');
        //$this->load->model('messages_model');
        $this->load->model('messages_model', 'send_messages');


        // custom library in codeigniter


        $this->appInfoFile = APPPATH.'libraries/dropbox/app-info.json';

       $redirect_uri ='https://www.domainname.com/knowledge/add/';

        $requestPath = $this->init();

        session_start();

        validate_user();
    }

    public function index($msg = NULL)
    {
        $session_data = $this->session->all_userdata();
        $data['msg'] = $msg;

        if (isset($session_data["validated"]) && $session_data["validated"] == '1') {
            $data['title'] = 'Knowledge Center';
            $data['records'] = $this->knowledge_model->get_all_rec();
          // echo "<pre>".print_r($data['records'],true)."</pre>";exit;
            $this->load->view('includes/header', $data);
            $this->load->view('includes/sidebar', $data);
            $this->load->view('knowledge', $data);
            $this->load->view('includes/footer');
        } else {
            redirect(base_url());
        }
    }

    public function tag($msg = NULL)
    {
        $tagname = $this->uri->segment("3");
        $tagnamehits = $this->uri->segment("4");

        $session_data = $this->session->all_userdata();
        $data['msg'] = $msg;

        if (isset($session_data["validated"]) && $session_data["validated"] == '1') {
            $data['title'] = 'Knowledge Center';
            $data['update_rec'] = $this->knowledge_model->update_hits($tagnamehits);
            $data['records'] = $this->knowledge_model->get_notifyrec_bytags($tagname);
            //echo "<pre>".print_r($data['records'],true)."</pre>";exit;
            $this->load->view('includes/header', $data);
            $this->load->view('includes/sidebar', $data);
            $this->load->view('knowledge', $data);
            $this->load->view('includes/footer');
        } else {
            redirect(base_url());
        }
    }

    public function add()
    {
        //validate form input
        $this->form_validation->set_rules('subject', 'subject', 'required');
        $this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
        $seralizedtags = serialize($this->input->post('tagsar'));
        //echo "<pre>".print_r($seralizedArray,true)."</pre>";exit;



        // drop box upload filess

        if (isset($_FILES['attached_file']['name']) && !empty($_FILES['attached_file']['name'])) {

            $file_name= $_FILES['attached_file']['name'];
            $return_result=$this->upload_to_dropbox($file_name);

            $rev=$return_result['rev'];
            $mime_type=$return_result['mime_type'];
            $path=$return_result['path'];
            $size=$return_result['size'];
            $revision=$return_result['revision'];

        }


        if ($this->form_validation->run() == true) {

            $session_data = $this->session->all_userdata();
            $user_id = $session_data["userid"];

            $data = array(
                'user_id' => $user_id,
                'edit_by_userid' => $user_id,
                'subject' => $this->input->post('subject'),
                'tags' => $seralizedtags,
                'description' => $this->input->post('description'),
                'dropbox_rev'=>$rev,
                'dropbox_mim_type'=>$mime_type,
                'dropbox_path'=>$path,
                'dropbox_filesize'=>$size,
                'dropbox_revision'=>$revision,
            );


            $message=$this->input->post('subject');

            //for slack call
            if(isset($message)){

                $message=$message;
                $messageType = "Knowledge_center";

                $this->send_messages->send_message_on_slack($messageType);
            }


            //echo "<pre>" . print_r($data, true) . "</pre>";

            $insert_res = $this->knowledge_model->insert_rec($data);

            if ($insert_res != "conf") {
                if ($insert_res == "subject") {
                    $this->session->set_flashdata('message', "<p>Subject Name already exist.Please change Subject</p>");
                } else {
                    $this->session->set_flashdata('message', "<p>Error in Insertion.</p>");
                }
                echo '<script>window.location.href = "' . base_url() . 'knowledge/add";</script>';
            } else {
                $this->session->set_flashdata('message', "<p>Record added successfully.</p>");
                echo '<script>window.location.href = "' . base_url() . 'knowledge";</script>';

            }
        } else {
            //set the flash data error message if there is one
            $this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));

            $this->data['subject'] = array(
                'name' => 'subject',
                'class' => 'form-control round-input',
                'id' => 'subject',
                'placeholder' => 'Subject',
                'type' => 'text',
                'autofocus' => 'true',
                'data-required' => '1',
                'value' => $this->form_validation->set_value('subject'),
            );

            $this->data['tagdata'] = array(
                'name' => 'tagsar',
                'class' => 'form-control tags tags-input',
                'id' => 'tagsar',
                'type' => 'text',
                'autofocus' => 'true',
                'data-type' => 'tags',
                'value' => $this->form_validation->set_value('tagsar'),
            );
            $data['desc'] = $this->form_validation->set_value('description');

           // $data['dropbox']=$this->dropbox->dp();

            $msg = "";
            $data['title'] = 'Knowledge Center';
            $data['msg'] = $msg;
            $this->load->view('includes/header', $data);
            $this->load->view('includes/sidebar', $data);
            $this->load->view('add_knowledge', $this->data);
            $this->load->view('includes/footer');
        }
    }

    public function view($id)
    {
        $update_rec = $this->knowledge_model->get_rec_byid($id);



        $data['dropbox_detail']=array(
            "dropbox_rev"=> $update_rec[0]->dropbox_rev,
            "dropbox_mim_type"=> $update_rec[0]->dropbox_mim_type,
            "dropbox_path"=> $update_rec[0]->dropbox_path,
            "dropbox_filesize"=> $update_rec[0]->dropbox_filesize,
            "dropbox_revision"=> $update_rec[0]->dropbox_revision,
            );

        $data['subject_data'] = $update_rec[0]->subject;
        $data['tags_data'] = unserialize($update_rec[0]->tags);
        $data['desc'] = $update_rec[0]->description;

        $data['title'] = 'Knowledge Center';
        $this->load->view('includes/header', $data);
        $this->load->view('includes/sidebar', $data);
        $this->load->view('view_knowledge', $this->data);
        $this->load->view('includes/footer');
    }

    public function manage_notify()
    {
        $notifyid = $_POST["elid"];
        $notifytext = $_POST["notifytext"];
        $notify_rec = $this->knowledge_model->get_notifyrec_byid($notifytext);
        $ret_res = "<ul>";
        foreach ($notify_rec as $notify_record) {
            $ret_res .= "<li>" . $notify_record->subject . "</li>";
        }
        $ret_res .= "</ul>";
        echo $ret_res;
        exit;
    }

    public function update($id)
    {
        //validate form input
        $this->form_validation->set_rules('subject', 'subject', 'required');
        $this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));

        $update_rec = $this->knowledge_model->get_rec_byid($id);
        //echo "<pre>".print_r($update_rec[0],true)."</pre>";exit;
        $seralizedtags = serialize($this->input->post('tagsar'));

        if ($this->form_validation->run() == true) {

            $session_data = $this->session->all_userdata();
            $user_id = $session_data["userid"];

            $data = array(
                'edit_by_userid' => $user_id,
                'subject' => $this->input->post('subject'),
                'tags' => $seralizedtags,
                'description' => $this->input->post('description')
            );


            $recid = $this->input->post('recid');
            // echo "<pre>".print_r($data,true)."</pre>";exit;
            $update_res = $this->knowledge_model->update_rec($recid, $data);

            if ($update_res > 0) {
                $this->session->set_flashdata('message', "<p>Record Updated successfully.</p>");
                echo '<script>window.location.href = "' . base_url() . 'knowledge";</script>';
            } else {
                $this->session->set_flashdata('message', "<p>Error in Updation.</p>");
                echo '<script>window.location.href = "' . base_url() . 'knowledge/update/' . $recid . '";</script>';
            }


        } else {
            //set the flash data error message if there is one
            $this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));

            if (isset($update_rec)) {
                $this->data['recid'] = array(
                    'name' => 'recid',
                    'class' => 'form-control',
                    'id' => 'recid',
                    'type' => 'hidden',
                    'autofocus' => 'true',
                    'data-required' => '1',
                    'value' => $update_rec[0]->id,
                );

                $this->data['subject'] = array(
                    'name' => 'subject',
                    'class' => 'form-control round-input',
                    'id' => 'subject',
                    'placeholder' => 'Subject',
                    'type' => 'text',
                    'autofocus' => 'true',
                    'data-required' => '1',
                    'value' => $update_rec[0]->subject,
                );

                $tags_data = unserialize($update_rec[0]->tags);

                $this->data['tagdata'] = array(
                    'name' => 'tagsar',
                    'class' => 'form-control tags tags-input',
                    'id' => 'tagsar',
                    'type' => 'text',
                    'autofocus' => 'true',
                    'data-type' => 'tags',
                    'value' => $tags_data,
                );
                $data['desc'] = $update_rec[0]->description;

            } else {
                $this->session->set_flashdata('message', "<p>Update Record not found.</p>");
                echo '<script>window.location.href = "' . base_url() . 'knowledge";</script>';
            }
            $msg = "";
            $data['title'] = 'Knowledge Center';
            $data['msg'] = $msg;
            $this->load->view('includes/header', $data);
            $this->load->view('includes/sidebar', $data);
            $this->load->view('edit_knowledge', $this->data);
            $this->load->view('includes/footer');
        }
    }


       public function download_dbx_file(){

           $file_path = $_POST['dropbox_path'];
           $mime_type = $_POST['dropbox_mim_type'];

           $this->download_file($file_path,$mime_type);

       }


    public function del($id)
    {
        $this->knowledge_model->del_rec($id);
        $this->session->set_flashdata('message', "<p>Record Deleted successfully.</p>");
        redirect(base_url() . 'knowledge');
    }


    //  for upload to dropbox //


    function getAppConfig()
    {
        global $appInfoFile;

        try {
            $appInfo = dbx\AppInfo::loadFromJsonFile($this->appInfoFile);
        }
        catch (dbx\AppInfoLoadException $ex) {
            throw new Exception("Unable to load \"$this->appInfoFile\": " . $ex->getMessage());
        }

        $clientIdentifier = "examples-web-file-browser";
        $userLocale = null;

        return array($appInfo, $clientIdentifier, $userLocale);
    }

    function getClient()
    {
        if (!isset($_SESSION['access-token'])) {
            return false;
        }

        list($appInfo, $clientIdentifier, $userLocale) = $this->getAppConfig();
        $accessToken = $_SESSION['access-token'];
        return new dbx\Client($accessToken, $clientIdentifier, $userLocale,$appInfo->getHost());
    }

    function getWebAuth()
    {
        list($appInfo, $clientIdentifier, $userLocale) = $this->getAppConfig();
        $redirectUri = getUrl("dropbox-auth-finish");
        $csrfTokenStore = new dbx\ArrayEntryStore($_SESSION, 'dropbox-auth-csrf-token');
        return new dbx\WebAuth($appInfo, $clientIdentifier, $redirectUri, $csrfTokenStore, $userLocale);
    }

    function respondWithError($code, $title, $body = "")
    {
        $proto = $_SERVER['SERVER_PROTOCOL'];
        header("$proto $code $title", true, $code);
        echo renderHtmlPage($title, $body);
    }

    function getUrl($relative_path)
    {
        if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
            $scheme = "https";
        } else {
            $scheme = "http";
        }
        $host = $_SERVER['HTTP_HOST'];
        $path = getPath($relative_path);
        return $scheme."://".$host.$path;
    }

    function getPath($relative_path)
    {
        if (PHP_SAPI === 'cli-server') {
            return "/".$relative_path;
        } else {
            return $_SERVER["SCRIPT_NAME"]."/".$relative_path;
        }
    }

    function init()
    {
        global $argv;

        // If we were run as a command-line script, launch the PHP built-in web server.
        if (PHP_SAPI === 'cli') {
            launchBuiltInWebServer($argv);
            assert(false);
        }

        if (PHP_SAPI === 'cli-server') {
            // For when we're running under PHP's built-in web server, do the routing here.
            return $_SERVER['SCRIPT_NAME'];
        }
        else {
            // For when we're running under CGI or mod_php.
            if (isset($_SERVER['PATH_INFO'])) {
                return $_SERVER['PATH_INFO'];
            } else {
                return "/";
            }
        }
    }


    function launchBuiltInWebServer($argv)
    {
        // The built-in web server is only available in PHP 5.4+.
        if (version_compare(PHP_VERSION, '5.4.0', '<')) {
            fprintf(STDERR,
                "Unable to run example.  The version of PHP you used to run this script (".PHP_VERSION.")\n".
                "doesn't have a built-in web server.  You need PHP 5.4 or newer.\n".
                "\n".
                "You can still run this example if you have a web server that supports PHP 5.3.\n".
                "Copy the Dropbox PHP SDK into your web server's document path and access it there.\n");
            exit(2);
        }

        $php_file = $argv[0];
        if (count($argv) === 1) {
            $port = 5000;
        } else if (count($argv) === 2) {
            $port = intval($argv[1]);
        } else {
            fprintf(STDERR,
                "Too many arguments.\n".
                "Usage: php $argv[0] [server-port]\n");
            exit(1);
        }

        $host = "localhost:$port";
        $cmd = escapeshellarg(PHP_BINARY)." -S ".$host." ".escapeshellarg($php_file);
        $descriptors = array(
            0 => array("pipe", "r"),  // Process' stdin.  We'll just close this right away.
            1 => STDOUT,              // Relay process' stdout to ours.
            2 => STDERR,              // Relay process' stderr to ours.
        );
        $proc = proc_open($cmd, $descriptors, $pipes);
        if ($proc === false) {
            fprintf(STDERR,
                "Unable to launch PHP's built-in web server.  Used command:\n".
                "   $cmd\n");
            exit(2);
        }
        fclose($pipes[0]);  // Close the process' stdin.
        $exitCode = proc_close($proc);  // Wait for process to exit.
        exit($exitCode);
    }


    public function upload_to_dropbox($filename){

        if($filename != ''){

            try {

                $dbxClient = $this->getClient();

                $remoteDir = "/";
                if (isset($_POST['folder'])) $remoteDir = $_POST['folder'];

                $remotePath = rtrim($remoteDir, "/")."/".$filename;

                $fp = fopen($_FILES['attached_file']['tmp_name'], "rb");
                $result = $dbxClient->uploadFile($remotePath, dbx\WriteMode::add(), $fp);
                fclose($fp);
                //$str = print_r($result, true);

                return $result;

            } catch (Exception $e) {
                echo $e->getMessage();
                exit;
            }
        }
        else{
            echo "File does not exists";
            exit;
        }


    }

    public function download_file($file_path,$file_mime_type){

        if($file_path != '' && $file_mime_type != '' ) {

            try {
                $dbxClient = $this->getClient();

                $path = $file_path;
                $fd = tmpfile();

                $metadata = $dbxClient->getFile($path, $fd);
                header("Content-Type: $metadata[mime_type]");
                fseek($fd, 0);
                fpassthru($fd);
                fclose($fd);

            } catch (Exception $e) {
                echo $e->getMessage();
                exit;
            }
        }
        else{
            echo "Invalid Request";
            exit;
        }
    }
}

所以你的例子:

children = Child.where( #something)
children_parents = Parent.joins(:children).where(children: {id: children} )

grandchildren = Grandchildren.where(#something)
grandchildren_parents = Parent.joins(children: :grandchildren).where(grandchildren: {id: grandchildren}) 

grandchildren_parents = Parent.joins(children: :grandchildren).where.not(grandchildren: {id: nil}).distinct

答案 2 :(得分:0)

在红宝石中:

@users_with_questions = User.all.select{|u| u.questions.present? }
@users_with_answers   = User.all.select{|u| u.questions.present? && u.answers.present? }

class User < ActiveRecord::Base
  has_many :questions
  has_many :answers, :through => :questions
end

在一个SQL查询中(只有一种方法):

@users_with_questions = User.find(Question.pluck(:user_id).uniq!)
questions = Question.find(Answer.pluck(:question_id).uniq!)
@users_with_answers = User.find(questions.pluck(:user_id).uniq!)