渲染查询与阿贾克斯的Rails [英] Render queries with ajax in Rails

查看:111
本文介绍了渲染查询与阿贾克斯的Rails的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助或指导具有下列问题。我用ajax重新加载从数据库中动态查询每次都是变化的一个搜索表单。

的目的是根据在搜索表单中选择的PARAMS动态加载寄存器的N个。

我有这个code,让我做数据库查询和打印结果的指标。在code是工作的方式,最后每个迭代打印广场()在查询结果中的每个注册表。

控制器:

 高清clientsjson

      @search = Client.search(PARAMS [:Q])
      @clients = @ search.result

      respond_to代码做|格式|
        format.json {渲染:JSON => @clients}
      结束
  结束
 

JS文件

  $(文件)。就绪(函数(){
   $(.searchupdate).change(函数(){

    $ .getJSON(/客户/ clientsjson?+ $('#client_search')。序列化(),功能(数据){

        变量$ UL = $('< D​​IV>< / DIV>');

         $ ul.append(Data.Map中(功能(数据){
                变量$ INI ='< D​​IV CLASS = \面板的队友bgray-O \>< D​​IV CLASS = \行\>

                变量$ INICIO ='< D​​IV CLASS = \COL-XS-4 \ALIGN = \中央\>
                变量$ TITULO ='< H3风格=高度:45像素;宽度:100%溢出:隐藏><一类=H1小的href =/ ES /拍卖/+数据['身份证' ] +'>+数据['名称'] +'&所述; / a取代;&所述; / H3>'
                变量$ titulo2 ='< H5类=草书TXT灰色-LIG negrita字体衬线>市国家< / H5>
                变量$ titulo3 ='< H5类=草书TXT灰色-LIG negrita字体衬线>语言:< / H5>
                变量$ titulo4 ='<一个数据切换=莫代尔数据-ID =1标题=查看评论级=开放模式拍卖的href =#myModalc'+数据['身份证'] +'>< H5类=TXT-AUTO的风格=的margin-top:10px的>
          变量$ titulo5 ='评级:其中; IMG SRC =/资产/埃斯特雷亚-991be5754e32c5209a9b4c697cf93320.pngALT =埃斯特雷亚WIDTH =20高度=20/>< IMG SRC =/资产/埃斯特雷亚-991be5754e32c5209a9b4c697cf93320.pngALT =埃斯特雷亚WIDTH =20高度=20/>< IMG SRC =/资产/埃斯特雷亚-991be5754e32c5209a9b4c697cf93320.pngALT =埃斯特雷亚WIDTH =20高度= 20/>&所述; / H5>&所述; / a取代;'
                变量$翅='< / DIV>

              变量$列2 ='< D​​IV CLASS = \COL-XS-5 \ALIGN = \中央\>< BR>
              变量$ parte1 ='< H4类=negrita草书字体衬线>'+数据['日'] +'< / H4>
              变量$ parte2 ='< H3类=negrita草书字体衬线的风格=的margin-top:2px的>最高价格<跨度类=TXT  - 铁道部>'+数据['maximum_price'] + '< / SPAN>< / H3> < H5类=草书TXT的灰色LIG> Duración:'+数据['时间'] +'< / H5>
              变量$ parte3 ='< BR />< P类=的margin-top:-12px><一个数据切换=莫代尔数据-ID =1称号=买入的风格: 宽度:120px;类=开模态拍卖BTN BTN-莫拉多卢斯-BTN-铁道部的href =#myModal'+数据['身份证'] +'>大法会Avanzada< / A>< / P>
              变量$ column2fin ='< / DIV>

              变量$ column3 ='< D​​IV CLASS =COL-XS-3 DIV-一般ALIGN =中心的风格=填充>
              变量$列1 ='< p风格=的margin-top:20px的>< IMG SRC =/资产/投标c355299aa9a59c701f6768169153b0e6.jpgALT =买入WIDTH =75高度=50/ ><一个数据切换=莫代尔数据-ID =1称号=买入级=开放模式拍卖的href =#myModalbids'+数据['身份证'] +'的风格=保证金左:5px的>法会和LT; / A>< / P>
              变量$形式='< D​​IV CLASS =伯德色 - 猜拳的风格=填充顶:5像素;保证金顶:20px的><形式的novalidate =NOVALIDATE级=formtastic申办ID = new_bid行动=/ ES /投标接收字符集=UTF-8的方法=后><输入名称=UTF8类型=隐藏值=&放大器;#x2713; /><输入类型=隐藏名称=authenticity_token值=QkFLk2OiMkFyMx5eeYqsAWex8DVeSpAT2YOnr1sY3kOIXKj​​sx4F0GRHs7a6byMCReue0Y82EScIUWXSErRxnhA ==/>< D​​IV CLASS =隐藏输入可选的形式 - 组ID =bid_auction_id_input><跨度类=形标签><标签=bid_auction_id级=控制标签>拍卖< /标签>< / SPAN><跨度类=形式 - 包装><输入ID =bid_auction_id值=1类型=隐藏名称=竞标[auction_id]/>< / SPAN>< / DIV>< p align =left的风格=保证金左:5像素> Pujar<输入类=伯德色 - 猜拳的风格=宽度:100像素;文本对齐:右类型=文字值=0.0NAME =中标[金额]ID =bid_amount/>< / P>
          变量$窗口2 ='<输入类型=提交名称=提交值=投标快速级=BTN BTN-莫拉多卢斯-BTN-MORID =按钮出价的风格=保证金顶:5像素;保证金底:20像素数据加载文本=载入中...自动完成=关闭/>< /形式GT;< / DIV>
              变量$ column3fin ='< / DIV>

                变量$结束='< / DIV>< / DIV>




         返回$($ini+$inicio+$titulo+$titulo2+$titulo3+$titulo4+$titulo5+$fin+$column2+$parte1+$parte2+$parte3+$column2fin+$column3+$column1+$form+$form2+$column3fin+$end)
         }));

         $('#clientList1)HTML('')。
         $('#clientList1)空()追加($ UL)。



    });

  });
});
 

HTML:

 < D​​IV ID =clientList1>< / DIV>
 

嗯,正如我前面所说的,code的工作近乎完美。但我有两个主要问题。

1)模型的客户,有几个型号的父母,如:国家,城市,语言等JSON的查询只带来了标识,但不要让我得到这个名字进行打印。是这样的:client.country.name。所以,我怎么能访问到父母的模型,所以我可以打印的名称,而不是ID的

2 - )也有类似关于第一个问题,但与孩子的机型,是这样的:client.comments。一般情况下我该<%=渲染client.comments%>,但我不能从JSON做到这一点,所以这里的问题是我如何可以访问查询中的每个寄存器相关联的子模型

有一个更好的办法做到这一点?

感谢你在前进。

////更新

调用该本地主机后:?3000 /客户/ clientsjson.json Q =测试我的浏览器,这是输出:

  [{意见:[]},{意见:[]},{意见:[]}]
 

的Json生成文件:

  json.array! @clients做|客户端|
  json.id
  json.name
  json.rate
  json.address
  json.date
  json.numbercomments

  json.comments client.comments,:主题,:评论,:created_at

  json.country做
    json.name
  结束

  json.city做
    json.name
  结束

  json.language做
    json.name
  结束

结束
 

这是我在route.rb做了路由调用操作。

 获得客户端/ clientsjson'=> 客户#clientsjson:为=> clientsjson',:格式=> :JSON
 

解决方案

一个更好的办法是使用的JBuilder Rabl的这既让您轻松地在您的JSON响应相关的数据。

在这里,你的情况,你只需要在创建视图文件:

 应用程序/视图/客户/ clientjson.json.jbuilder
 

那么你的JBuilder看起来是这样的:

  json.array! @clients做|客户端|
  json.id client.id
  json.name client.name
  json.rate client.rate
  json.address client.address
  json.date client.date
  json.numbercomments client.numbercomments

  json.comments client.comments,:主题,:评论,:created_at

  json.country做
    json.name client.country.name
  结束

  json.city做
    json.name client.city.name
  结束

  json.language做
    json.name client.language.name
  结束

结束
 

然后改变你的控制器动作:

 高清clientsjson
  @search = Client.search(PARAMS [:Q])
  @clients = @ search.result

  respond_to代码做|格式|
    format.json
  结束
结束
 

这应该给你你需要的所有相关JSON的节点。

I need help or guidance with the following problem. I using ajax to reload dynamically queries from database each time is change in a search form.

The purpose is to dynamically load N quantity of register according to the params selected in the search form.

I have this code that allow me to made queries to the database and printed the results in the index. The code is working by the way, and finally each iteration prints a "square" () for each registry in the result of the query.

Controller:

 def clientsjson

      @search  =  Client.search(params[:q])
      @clients = @search.result

      respond_to do |format|
        format.json { render :json => @clients }
      end
  end

Js file

$(document).ready(function() {
   $( ".searchupdate" ).change(function() {

    $.getJSON("/client/clientsjson?"+$('#client_search').serialize(), function (data) {

        var $ul = $('<div></div>');

         $ul.append(data.map(function(data) {
                var $ini= '<div class=\"panel-mate bgray-o\"><div class=\"row\">'

                var $inicio='<div class=\"col-xs-4\" align=\"center\">'
                var $titulo='<h3 style="height:45px; width:100% overflow:hidden"><a class="h1-small" href="/es/auctions/'+data['id']+'">'+data['name']+'</a></h3>'
                var $titulo2='<h5 class="cursive txt-gray-lig negrita font-serif">City, Country</h5>'
                var $titulo3='<h5 class="cursive txt-gray-lig negrita font-serif">Idioma:</h5>'
                var $titulo4='<a data-toggle="modal" data-id="1" title="View comments" class="open-modal-auction" href="#myModalc'+data['id']+'"><h5 class="txt-auto" style="margin-top: 10px">'
          var $titulo5='Rating:<img src="/assets/estrella-991be5754e32c5209a9b4c697cf93320.png" alt="Estrella" width="20" height="20" /><img src="/assets/estrella-991be5754e32c5209a9b4c697cf93320.png" alt="Estrella" width="20" height="20" /><img src="/assets/estrella-991be5754e32c5209a9b4c697cf93320.png" alt="Estrella" width="20" height="20" /></h5></a>'
                var  $fin='</div>'

              var $column2='<div class=\"col-xs-5\" align=\"center\"><br>'
              var $parte1 ='<h4 class="negrita cursive font-serif">'+data['date']+'</h4>'
              var $parte2 ='<h3 class="negrita cursive font-serif" style="margin-top: 2px">Maximum Price<span class="txt-mor ">'+data['maximum_price']+'</span></h3> <h5 class="cursive txt-gray-lig"> Duración: '+data['duration']+'</h5>'
              var $parte3 ='<br/><p style="margin-top:-12px"><a data-toggle="modal" data-id="1" title="Bid" style:"width:120px;" class="open-modal-auction btn btn-morado luz-btn-mor" href="#myModal'+data['id']+'">Puja Avanzada</a></p>'
              var $column2fin='</div>'

              var $column3='<div class="col-xs-3 div-general" align="center" style="padding:">'
              var $column1='<p style="margin-top: 20px"><img src="/assets/bid-c355299aa9a59c701f6768169153b0e6.jpg" alt="Bid" width="75" height="50" /><a data-toggle="modal" data-id="1" title="Bid"  class="open-modal-auction" href="#myModalbids'+data['id']+'" style="margin-left:5px">Pujas</a></p>'
              var $form='<div class="borde-color-mora" style="padding-top:5px; margin-top:20px"><form novalidate="novalidate" class="formtastic bid" id="new_bid" action="/es/bids" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="authenticity_token" value="QkFLk2OiMkFyMx5eeYqsAWex8DVeSpAT2YOnr1sY3kOIXKjsx4F0GRHs7a6byMCReue0Y82EScIUWXSErRxnhA==" /><div class="hidden input optional form-group" id="bid_auction_id_input"><span class="form-label"><label for="bid_auction_id" class=" control-label">Auction</label></span><span class="form-wrapper"><input id="bid_auction_id" value="1" type="hidden" name="bid[auction_id]" /></span></div><p align="left" style="margin-left:5px">Pujar  <input class="borde-color-mora" style="width: 100px; text-align:right" type="text" value="0.0" name="bid[amount]" id="bid_amount" /></p>'
          var $form2='<input type="submit" name="commit" value="Bid Fast" class="btn btn-morado luz-btn-mor" id="button-bid" style="margin-top:5px; margin-bottom:20px" data-loading-text="Loading..." autocomplete="off" /></form></div>'
              var $column3fin='</div>'

                var $end= '</div></div>'




         return $($ini+$inicio+$titulo+$titulo2+$titulo3+$titulo4+$titulo5+$fin+$column2+$parte1+$parte2+$parte3+$column2fin+$column3+$column1+$form+$form2+$column3fin+$end)
         }));

         $('#clientList1').html('');
         $('#clientList1').empty().append($ul);



    });

  });
});

Html:

<div id="clientList1"></div>

Well, as I said before, the code work almost perfectly. But I have two main issues.

1-)The model client, have several model parents like: country, city, languages, etc. The json query only brings the IDs but dont let me to get the name for printing. Something like: "client.country.name". So how I can access to the parents models so I can print the names and not the IDs

2-) Something similar to the first issue but with the child models, something like: "client.comments". Normally I would this <%= render client.comments %> but I can't do this from JSON, so the question here is how I can access the child model associated with each register in the query.

There is a better way to do this?

thank you in advance.

////Update

After of calling this localhost:3000/client/clientsjson.json?q=test in my browser, this is the output:

[{"comments":[]},{"comments":[]}, {"comments":[]}]

Json Builder file:

json.array! @clients do |client|
  json.id
  json.name
  json.rate
  json.address
  json.date
  json.numbercomments

  json.comments client.comments, :subject, :comment,:created_at

  json.country do
    json.name
  end

  json.city do
    json.name
  end

  json.language do
    json.name
  end

end

And here is the route I made in route.rb to call the action.

get 'client/clientsjson' => "clients#clientsjson", :as => 'clientsjson', :format => :json

解决方案

A better way would be to use jbuilder or RABL which both allow you to easily include associated data in your json response.

In your case here, you would simply need to create a view file at:

app/views/clients/clientjson.json.jbuilder

Then your jbuilder would look something like:

json.array! @clients do |client|
  json.id client.id
  json.name client.name
  json.rate client.rate
  json.address client.address
  json.date client.date
  json.numbercomments client.numbercomments

  json.comments client.comments, :subject, :comment, :created_at

  json.country do
    json.name client.country.name
  end

  json.city do
    json.name client.city.name
  end

  json.language do
    json.name client.language.name
  end

end

Then change your controller action to:

def clientsjson
  @search  =  Client.search(params[:q])
  @clients = @search.result

  respond_to do |format|
    format.json
  end
end

Which should give you all the associated json nodes you need.

这篇关于渲染查询与阿贾克斯的Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆