jeudi 24 septembre 2015

Rails 4 - Display data inside a bootstrap modal via ajax

I have a pretty simple Ruby On Rails app with bootstrap 3 for the front end: I have Deals, and each Deal has_many Opportunities.

On each Deal page (url of deal 1 is like myapp.com/id=1), I want to have a textual link that says "view deal's opportunities" and that must trigger when clicked the appearance of content inside a Bootstrap modal.

Very basic but for specific reasons, I wish to load the content of the modal via Ajax.(the content is not visible when users load the Deal page but only when they click on the link 'view deal's opportunities'

I found many resources online for Rails4/ajax/Forms and other stuff with Ajax but not a simple "display content/text" inside a modal via Ajax. Should be easy but I'm stuck.

controller/deals_controller.rb

def showcase    
    deals = Deal.friendly.find(params[:id])   

    respond_to do |format|
      format.html # showcase.html.erb
      format.json { render json: @deal }
    end
end 

def show_opportunities

    @opportunities = Opportunity.where('deal_id = ? AND deal_type = ?',
                             @deal.id, "high tech").first

    respond_to do |format|
      format.js
    end

  end

app/views/deals/showcase.html.erb

this is the beginning
<%= render 'deals/deal_info_zone' =>
this is the end

views/deals/_deal_info_zone.html.erb

<div id="zoneA">  

  <div style="color:red;padding-top: 150px;">
    <%= link_to "view infos of Opportunities", deal_opportunities_modal_path, remote: true %>
  </div>
</div>

Here is the modal I'd like to trigger via ajax: views/deals/opportunity_modal

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">

      <div class="modal-body"> 

          <%= @opportunity.name %> <br/>     

      </div>

    </div>
  </div>
</div>

routes.rb

match '/deals/:id', # this is the Deal page
    to:   'deals#showcase',
    via:  'get',
    as:   :deal_page

match '/opportunity_modal',
    to:   'deals#show_opportunities',
    via:  'get',
    as:   :deal_opportunities_modal

I'm a rookie in RoR and have never used ajax, ujs maybe... I feel it's missing things like javascript code and xhr request...

The current situation is this one: when I go on a Deal page (for ex page /deal id=1) the textual link "view infos of Opportunities". and the browser points to http://localhost:3000/opportunity_modal but it does not trigger anything when I click on it. Nothing happens. Nothing gets displayed btw on firebug console.

Can anyone help? thanks

Aucun commentaire:

Enregistrer un commentaire