是否可以获取js数组,用户控制器名称的值?如果我有一个具有名称,用户名,密码,生日等的控制器,我想在javascript数组中只检索名称,如下所示:
var user_names = ["firstuser","seconduser","thirduser"]
我该怎么做?
另一件事是我想在主页面(/ index)中使用它来搜索输入。我认为控制器是application_controller,但是现在,我在用户控制器中进行测试。
贝娄是控制者。它不是一个“用户”它的学生(aluno)。 alunos2
只是一个考验。
# encoding: utf-8
class AlunosController < ApplicationController
before_action :set_aluno, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
helper_method :sort_column, :sort_direction
def autocomplete
render json: Aluno.search(params[:query], autocomplete: true, limit: 10).map(&:nome)
end
# GET /alunos
# GET /alunos.json
def index
@alunos2 = Aluno.all
@alunos = Aluno.search(params[:search]).order("LOWER(#{sort_column}) #{sort_direction}").paginate(:per_page => params[:npage], :page => params[:page])
end
# GET /alunos/1
# GET /alunos/1.json
def show
end
# GET /alunos/new
def new
@aluno = Aluno.new
end
# GET /alunos/1/edit
def edit
end
# POST /alunos
# POST /alunos.json
def create
@aluno = Aluno.new(aluno_params)
respond_to do |format|
if @aluno.save
format.html { redirect_to alunos_url, notice: 'Aluno foi criado com sucesso.' }
format.json { render :show, status: :created, location: @aluno }
else
format.html { render :new }
format.json { render json: @aluno.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /alunos/1
# PATCH/PUT /alunos/1.json
def update
respond_to do |format|
if @aluno.update(aluno_params)
format.html { redirect_to @aluno, notice: 'Aluno foi atualizado com sucesso.' }
format.json { render :show, status: :ok, location: @aluno }
else
format.html { render :edit }
format.json { render json: @aluno.errors, status: :unprocessable_entity }
end
end
end
# DELETE /alunos/1
# DELETE /alunos/1.json
def destroy
@aluno.destroy
respond_to do |format|
format.html { redirect_to alunos_url, notice: 'Aluno foi removido com sucesso.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_aluno
@aluno = Aluno.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def aluno_params
params.require(:aluno).permit(:nome, :sobrenome, :nascimento, :responsavel, :cpf, :rg, :telefone, :celular, :email, :rua, :numero, :bairro, :complemento, :cidade, :estado)
end
def sort_column
Aluno.column_names.include?(params[:sort]) ? params[:sort] : "nome"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
# A list of the param names that can be used for filtering the Product list
#private
#def filtering_params(params)
#params.slice(:status, :location, :starts_with)
#end
end
答案 0 :(得分:0)
我使用下面的代码解决了这个问题
<%= javascript_tag do %>
var alunos_list = <%= @alunos2.to_json.html_safe %>;
var alunos_names = [];
jQuery.each(alunos_list, function(i, val) {
alunos_names.push(alunos_list[i].nome + ' ' + alunos_list[i].sobrenome);
});
<% end %>