I wan't to add an active record association to the dom, but am having trouble.
I have this editor class
.editing
.row
.col-sm-3
.col-sm-8
.text-left
#font-20
.title-font
.title-editor
As it is, the editor is empty which is what it's supposed to do. But when someone edits their title, I wan't to be able to show their saved title. The loading of this editor is with jquery and there is no page refreshing.
In my javascript I have access to the id of the object I want the title from
js:
var draft = $(e.target).attr('class');
var id = id.slice(draft);
With that id I want to add the objects title to the dom.
Something like this would be ideal, but I don't think it's possible.
var title = <%= Draft.find_by(id: $id).title %>
$('.title-editor').html(title);
How can I do something like this?
Well, you will need to use ajax eventually...
First, you can make a slight change to your drafts_controller.rb
. One of the ways to do this is the following:
def show # @draft is supposingly defined in a before_action callback
respond_to do |format|
format.html
format.json {
render :json => {'title' = @draft.title}
}
end
end
So, if your @draft
is : {id:1, title: 'hello'}, you will have:
http://your.app.com/drafts/1.json
which will render {"title":"hello"}
.
How do you use this? Easy... In your view, you bind this code to an event that will fire it.
$.ajax({
type: "GET",
url: "/drafts/"+id+".json",
dataType: "json",
success: function(data) {
$('.title-editor').html(data.title);
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.