dynamic content in ajax while rendering partial vi

2019-08-09 18:54发布

问题:

How do I get dynamic content when user clicks on different links?

views/dashboard/index.html.haml

.container
  - @trips.each do |trip|
    = link_to trip.id, quick_view_trips_path, remote: true

I'm pretty sure the quick_view_trips_path is incorrect as all the links are this:

<a href="/trips/quick_view">1</a>
<a href="/trips/quick_view">13</a>
<a href="/trips/quick_view">51</a>

Somehow I need to make these links dynamic, and then when user clicks on it, the modal window would be dynamic too.

If I replace quick_view_trips_path with just trip

= link_to trip.id, trip, remote: true

Nothing happens, and the url changes to the correct url, but my modal window doesn't get rendered through ajax. Here's an example of what the url looks like now:

<a href="/trips/slug-title-url-correct">1</a>

In addition to what I'm trying to accomplish with dynamic content, is there a way to maybe change my url like so:

<a href="/trips/slug-title-url-correct?quick_view=on">1</a>

Is it possible to get ?quick_view=on appending to end of URL and make everything work again?

Here are the rest of my code:

views/trips/quick_view.js.erb

$('body').append('<%= j render partial: "trips/quick_view" %>');

views/trips/_quick_view.html.haml

.root-container
  = @trip.title
  = @trip.image
  = @trip.more_details

This doesn't work either right now, as my application returns undefined method

routes.rb

resources :trips do
  collection do
    get 'quick_view'
  end
end

trips_controller.rb

def quick_view
  respond_to do |format|
    format.html # quick_view.html.erb
    format.js # quick_view.js.erb
    format.json { render json: @trip }
  end
end

Do I need to add anything to this controller as well to ensure the correct content will be generated through the partial?

回答1:

How about this way,

  1. Path

    link_to trip.id, quick_view_trips_path(:js, trip_id: trip.id), remote: true
    

    This will render, <a href="/trips/quick_view.js?trip_id=1">1</a>

  2. Controller

    def quick_view
      @trip = Trip.find(params[:trip_id])
      respond_to do |format|
        format.html # quick_view.html.erb
        format.js # quick_view.js.erb
        format.json { render json: @trip }
      end
    end
    

    It will respond views/trips/quick_view.js.erb file