2014-12-04 106 views
0

我不想将活动记录关联添加到dom,但遇到问题。使用rails活动记录关联创建javascript变量

我这个编辑器类

.editing 
    .row 
    .col-sm-3 
    .col-sm-8 
     .text-left 
     #font-20 
      .title-font 
      .title-editor 

正因为如此,该编辑器是空的这是它应该做的。但是当有人编辑他们的标题时,我无法显示他们保存的标题。这个编辑器的加载是使用jquery,并且没有页面刷新。

在我的javascript我有

JS获得我想要的标题对象的ID:

var draft = $(e.target).attr('class'); 
var id = id.slice(draft); 

使用该ID我想要的对象标题添加到DOM。
这样的事情会很理想,但我不认为这是可能的。

var title = <%= Draft.find_by(id: $id).title %> 
$('.title-editor').html(title); 

我该怎么做这样的事情?

回答

0

那么,你就需要最终用ajax ...

首先,你可以做一个细微的变化,以您的drafts_controller.rb。一要做到这一点的方法是:

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 

因此,如果您@draft为:{ID:1,标题: '你好'},你将有:
http://your.app.com/drafts/1.json这会使{"title":"hello"}

你如何使用它?简单...在您看来,您将此代码绑定到将会触发它的事件。

$.ajax({ 
    type: "GET", 
    url: "/drafts/"+id+".json", 
    dataType: "json", 
    success: function(data) { 
     $('.title-editor').html(data.title); 
    } 
});