Answer the question
In order to leave comments, you need to log in
What is the correct way to convert HTML to a string for a JSON object in Rails?
There is a view that is designed to respond with JSON to an
AJAX request:
{
"description": "<%= @homework.description %>",
"form_link": "<%= classroom_homework_path(classroom_id, @homework) %>",
"attachment_ids": "<%= @homework.attachments.ids.join " " %>",
"html_id" : "homework<%= @homework.id %>"
<% if @homework.subject_id %>
,"tag": <%= @homework.subject_id %>
<% end %>
,"files": [
<% first = true %>
<% @homework.attachments.each do |f| %>
<% if first %>
<% first = false %>
<% else %>
,
<% end %>
"<%= (render partial: "materials/file", object: f, formats: :html).to_json %>"
<% end %>
]
}
<div class="this-material this-material-preview show-X">
<div class = 'del-this-file'>
<a class = 'X18' attachment = '<%= file.id%>'>×</a>
</div>
<div class="files-image type-document">
</div>
<div class="name-files">
<%= link_to truncate(file.file.file.filename, length: 30), file.file.url %>
</div>
</div>
Answer the question
In order to leave comments, you need to log in
You need jbuilder (DSL for json generation) or active_model_serializers (implements object approach to json generation)
It is very difficult to parse something, of course. And what should be in the files key, my brain, personally, could not compile in 2 minutes.
Break down the "refactoring", if you can call it that, into the following steps:
1. Throw in the HTML partial
2. Instead of manually collecting text JSON in the view, collect the ruby hash in the controller and call to_json
. For example:
def my_action
res = {
description: @homework.description,
...
html_id: "homework#{@homework.id}"
}
res[:tag] = @homework.subject_id if @homework.subject_id
end
res.to_json
would give the desired result. each_with_index
ActionController::Base.new.render(...)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question