[英]Creating a javascript variable with a rails active record association
I wan't to add an active record association to the dom, but am having trouble. 我不想向dom添加活动记录关联,但是遇到了麻烦。
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.
该编辑器的加载是通过jquery进行的,没有页面刷新。
In my javascript I have access to the id of the object I want the title from 在我的JavaScript中,我可以访问我想要标题的对象的ID
js: 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. 有了该ID,我想将对象标题添加到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... 好吧,您最终将需要使用ajax ...
First, you can make a slight change to your drafts_controller.rb
. 首先,您可以对
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: 因此,如果您的
@draft
是:{id:1,title:'hello'},您将拥有:
http://your.app.com/drafts/1.json
which will render {"title":"hello"}
. http://your.app.com/drafts/1.json
,它将呈现{"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);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.