简体   繁体   中英

How to query database and filter results (Ember.js + Rails)

UPDATE: I've found a way that works, though it's not very flexible, by taking the params hash and comparing its keys to my model's column names. I then take that array of names and map it to a hash, that I then use in my ActiveRecord query. There must be a better way?

  def index
    if params
      hash = {}
      attributes = User.column_names & params.keys
      attributes.each do |attribute|
        hash.merge!(attribute.to_sym => params[attribute.to_sym])
      end
      @users = User.where(hash)
    else
      @users = User.all
    end
    respond_with @users
  end

BACKGROUND: I've hooked up an Ember app to a Rails JSON API and have figured out how to query the database using Ember-Data. Below is an example in Coffeescript:

App.UsersRoute = Ember.Route.extend
  model: ->
    # Step 1: Query database for all users
    @store.find('user')

    # Step 2: Filter results (keep male users named "Steve")
    @store.filter 'user', (user)->
      user.get('name') == "Steve" && user.get('gender') == "Male"

OBJECTIVE: I'm wondering if this is the best way to go about this? Wouldn't querying for all users get increasingly difficult as the number of users increases?

I'm thinking a good alternative would be to include the query as parameters on my initial query, like so:

@store.find 'user', {name: "Steve", gender: "Male"}
# Sends JSON request to /users.json?name=Steve&gender=Male

If this is a better approach, I am stumped as to how to make Rails take these two parameters and query the database for them. Below is my Rails controller that responds to the above request:

class Api::V1::UsersController < ApplicationController
  respond_to :json

  def index
    respond_with User.all
  end
end

In order to accommodate the above request, I'd have to do something like this:

  def index
    respond_with User.where(name: params[:name], gender: params[:gender])
  end

But this would not accommodate any additional queries, or queries that don't have both of these params set. Which of these two approaches is best?

You can try doing like this, it allows you to customize your where and other clauses depending upon input params:-

def index
    @user = User
if params[:name].present? && params[:gender].present?
    @user =  @user.where(name: params[:name], gender: params[:gender])
end

@user = @user.all
.....
  end

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.

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