jquery - How to load field with ajax in index view on rails -


i have structure on views of class

views/cards/index

<% render @cards %> 

views/cards/_card

<div class="col-md-4">   <p><%= card.name %></p>   <p><a href="#" class="link-show-phone">show phone</a></p>   <p><div id="show-phone-<%= card.id %>"></div></p>   <p><a href="#" class="link-show-email">show email</a><p>   <p><div id="show-email-<%= card.id %>"></div><p> </div> 

controllers/cards_controller

def index   @cards= card.all end  def card_params    params.require(:card).permit(       :name,       :phone,       :email end 

i starting ajax , know best solution make requests using jquery , native rails resources.

i example click on link

<a href="#" class="link-show-email">show email</a>

render field card.email , append

<div id="show-email-<%= card.id %>"></div>

this sample html, can changed, if need correction or more information can provide! lot

note if use partial render each of cards record, you'll have multiple classes same id, so, idea add id of object useless, try editing cards partial like:

<div class="col-md-4">   <p><%= card.name %></p>   <p>     <a href="#" class="link-show-phone-<%= card.id %>">       show phone     </a>   </p>   <p><div id="show-phone-<%= card.id %>"></div></p>   <p>     <a href="#" class="link-show-email-<%= card.id %>">       show email     </a>   <p>   <p><div id="show-email-<%= card.id %>"></div><p> </div> 

this way whenever click on show phone or email, you'll attribute want get, , id of record.

so can create script listeners a elements, like:

<script type="text/javascript">   $("[class^='link-show']").click(function(e) {     e.preventdefault()     let attrs = $(this).attr('class').split('-')     let attr  = attrs[2]     let el    = attrs.pop()     $.get({ url: '/cards/' + el + '/' + attr })   }); </script> 

there add click event listener each element starts class link-show, attribute , id, prevent default behavior, , make request.

as url points cards/:id/:attribute need create method , route:

def show_attribute   @card = card.find(params[:id])   @attribute = @card[params[:attribute]] end 

here method recevies id , attribute params, use find card passed id, , set attribute needed variable called @attribute.

the route specifies params expect , tells controller , method:

get '/cards/:id/:attribute', to: 'cards#show_attribute' 

as need js.erb file update content in dom:

$('#show-<%= "#{params[:attribute]}-#{params[:id]}" %>').html('<%= escape_javascript(@attribute) %>') 

it gets #show- element, depending on attribute need, , use params[:id] identify it, sets attribute needed created in controller.

hope helps.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -