Getting a collection via Ajax for display

All I am trying to do is populate the collection in the view when the user clicks the button. But I feel like making it too hard and not working. See my code - where am I going wrong?

Click handler:

 $('#filterrific_results').find('.followup-injury').on('click', function(e){
            e.preventDefault();


             $.ajax({
                    url: "/assessments/followups",
                    type: "POST",
                    data: {patient_id: patient_id},
                    success: function(data){
                      console.log(data)
                    },
                    error: function(err) {
                      console.log(err);
                    }
                 });

         });

      

Controller action:

 def followups
    @patient = Patient.find(params[:patient_id])
    @assessments = @patient.assessments
    render :followups
  end

      

Followups.js.erb:

$('.modal-body').html("<%= render partial: 'followup', :assessments=> @assessments %>").html_safe

      

_followup.html.erb:

<%= @assessments.each do |assessment| %>
 <%= assessment.name %>
<% end %>

      

Users clicks button -> Data is sent to controller -> Controller displays Javascript -> Javascript displays partial html.

Am I making it too complicated? Also my html is not even rendering (estimate .name)

+3


source to share


1 answer


Your partial (currently named: _followup.html.erb

in your example) should be just code to create one line, Rails will iterate over it for you, and you should call it after the model it represents, i.e.

 # app/views/assessments/_assessment.html.erb
 <%= assessment.name %>

      

Then in your view, app/views/assessments/followups.html.erb

you should use this partial like so:

<%= render @assessments %>

      



... yes that's all it takes, Rails will iterate over it automatically, setting a local variable assessment

inside a partial for every object within @assessments

.

So the last snippet is yours followups.js.erb

, basically you want exactly the same string render

as you put in your HTML file, but just wrap it in escape_javascript

so it gets passed correctly to the JS function html()

:

$('.modal-body').html("<%= escape_javascript render @assessments %>")

      

What is it.

+2


source







All Articles