【问题标题】:How do I render my JS erb?如何渲染我的 JS erb?
【发布时间】:2015-03-20 13:44:20
【问题描述】:

我的NodesController 上有一个save_video 操作:

format.html { redirect_to video_tag_users_path(@video) }

我想要发生的是,当它调用该操作时,它应该呈现我的tag_users.js.erb,但事实并非如此。

这是我的tag_users 操作:

  def tag_users
    authorize! :read, @family_tree
    @video = Video.find(params[:video_id])
    @node = @video.node

    respond_to do |format|
      format.html
      format.js
    end

    redirect_to root_path
  end

这是正在发生的事情的日志:

Redirected to http://localhost:3000/videos/164/tag_users
Completed 302 Found in 23ms (ActiveRecord: 12.3ms)


Started GET "/videos/164/tag_users" for 127.0.0.1 at 2015-03-20 08:24:09 -0500
Processing by VideosController#tag_users as HTML
  Parameters: {"video_id"=>"164"}
# truncated for brevity
  Rendered videos/tag_users.html.erb within layouts/application (0.2ms)

这是我想要渲染的文件:tag_users.js.erb

$("#add-video-step-3").html("<%= escape_javascript(render 'videos/tag_users_in_video') %>");

然后渲染这个模态_tag_users_in_video.html.erb:

<div class="bootstrap-styles" id="add-video-step-5"> 
 <div class="modal-header">
      <div class="titles clearfix">
          <h2>Tag Users</h2>
          <p><i>Step 3 of 3</i></p>
      </div>
  </div>
  <div class="modal-body">
    <div class="content">
            <div>Tag someone</div>
            <%= simple_form_for @node, url: add_tagged_user_node_path(@node), method: :post do |f| %>
              <%= f.error_notification %>

              <div class="form-inputs">
                    <%= f.association :user, label: "Users", collection: @users, as: :check_boxes, checked: @node.user_tags %>
              </div>                            

              <div class="form-actions">
                <%= f.button :submit, class: "btn btn-success ladda-button" %>
              </div>
            <% end %>
    </div>
  </div>
  <div class="modal-footer">
  </div>
</div>

编辑 1

所以我将tag_users 操作中的respond_to 块更改为:

render 'tag_users.js'  

但现在它实际上是在渲染 JS 而不是执行它并渲染我希望它渲染的模态。

即这是我的浏览器中显示的内容,它重定向到 URL localhost/videos/167/tag_users.js:

$("#add-video-step-3").html("<div class=\"bootstrap-styles\" id=\"add-video-step-5\"> \n <div class=\"modal-header\">\n      <div class=\"titles clearfix\">\n          <h2>Tag Users<\/h2>\n          <p><i>Step 3 of 3<\/i><\/p>\n      <\/div>\n  <\/div>\n  <div class=\"modal-body\">\n    <div class=\"content\">\n           <div>Tag someone<\/div>\n           <form accept-charset=\"UTF-8\" action=\"/nodes/40/add_tagged_user\" class=\"simple_form edit_node\" id=\"edit_node_40\" method=\"post\" novalidate=\"novalidate\"><div style=\"display:none\"><input name=\"utf8\" type=\"hidden\" value=\"&#x2713;\" /><input name=\"authenticity_token\" type=\"hidden\" value=\"Jj8CsHGzcNJJuJn9HGWjNaSjIfSJaZ8N81vmZ+Zp6KQ=\" /><\/div>\n             \n                            \n            <div class=\"form-inputs\">\n                 <div class=\"control-group check_boxes optional node_user\"><label class=\"check_boxes optional control-label\">Users<\/label><div class=\"controls\"><label class=\"checkbox\"><input class=\"check_boxes optional\" id=\"node_user_id_true\" name=\"node[user_id][]\" type=\"checkbox\" value=\"true\" />Yes<\/label><label class=\"checkbox\"><input class=\"check_boxes optional\" id=\"node_user_id_false\" name=\"node[user_id][]\" type=\"checkbox\" value=\"false\" />No<\/label><input name=\"node[user_id][]\" type=\"hidden\" value=\"\" /><\/div><\/div>\n            <\/div>                           \n\n              <div class=\"form-actions\">\n                <input class=\"btn btn btn-success ladda-button\" name=\"commit\" type=\"submit\" value=\"Update Node\" />\n              <\/div>\n<\/form>    <\/div>\n  <\/div>\n  <div class=\"modal-footer\">\n  <\/div>\n<\/div>");

这基本上意味着它没有像我期望的那样渲染 HTML,而只是从视图 _tag_users_in_video.html.erb partial 中吐出 HTML。

我希望它弹出一个看起来像带有id=add-video-step-3 的模态但具有我在_tag_users_in_video.html.erb 中指定的内容的模态。

编辑 2

上述动作的服务器日志是:

Started GET "/videos/168/tag_users.js" for 127.0.0.1 at 2015-03-20 10:03:56 -0500
Processing by VideosController#tag_users as JS
  Parameters: {"video_id"=>"168"}
  User Load (1.3ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 57  ORDER BY "users"."id" ASC LIMIT 1
  FamilyTree Load (0.9ms)  SELECT  "family_trees".* FROM "family_trees"  WHERE "family_trees"."user_id" = $1 LIMIT 1  [["user_id", 57]]
   (1.1ms)  SELECT COUNT(*) FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 57]]
  Membership Load (1.6ms)  SELECT "memberships".* FROM "memberships"  WHERE "memberships"."user_id" = 57 AND "memberships"."family_tree_id" = 57
  Video Load (1.1ms)  SELECT  "videos".* FROM "videos"  WHERE "videos"."id" = $1 LIMIT 1  [["id", 168]]
  Node Load (1.1ms)  SELECT  "nodes".* FROM "nodes"  WHERE "nodes"."media_id" = $1 AND "nodes"."media_type" = $2 LIMIT 1  [["media_id", 168], ["media_type", "Video"]]
  ActsAsTaggableOn::Tag Load (1.8ms)  SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = $1 AND "taggings"."taggable_type" = $2 AND "taggings"."context" = 'user_tags'  [["taggable_id", 41], ["taggable_type", "Node"]]
  Rendered videos/_tag_users_in_video.html.erb (23.6ms)
  Rendered videos/tag_users.js.erb (25.5ms)
Completed 200 OK in 196ms (Views: 23.1ms | ActiveRecord: 84.6ms)

编辑 3

所以我按照您的建议将 JS 渲染添加到我的 save_video 操作中的 format.html 中。这是代码:

  respond_to do |format|
    if @node
      format.html { render 'tag_users.js' }
      format.js
    end
  end

结果如下:

而我试图让它看起来像这样:

编辑 4

这是我的控制器中的save_video 方法(我留下了注释掉的代码以查看已尝试的内容均未成功):

  def save_video
    authorize! :read, @family_tree
    @video = Video.find(params[:video_id])
    if params[:status].to_i == 200
      @video.update_attributes(:yt_video_id => params[:id].to_s, :is_complete => true)
      @node = current_user.nodes.create!(family_tree: @family_tree, media: @video, name: @video.title, circa: @video.circa)    

      if @node
        render 'tag_users.js'
      end

      # respond_to do |format|
      #   if @node
      #     format.html {  }
      #     format.js
      #   end
      # end

    else
      Video.delete_video(@video)
    end

    # respond_to do |format|
    #   format.html { redirect_to video_tag_users_path(@video, @node) }
    #   format.js
    # end

    # redirect_to root_path
    # redirect_to video_tag_users_path(@video, @node)
  end

这是save_video 操作的这种排列的服务器日志:

Started GET "/videos/172/save_video?status=200&id=bMaCxSIbJYU" for 127.0.0.1 at 2015-03-20 13:39:19 -0500
Processing by VideosController#save_video as HTML
  Parameters: {"status"=>"200", "id"=>"bMaCxSIbJYU", "video_id"=>"172"}
  User Load (1.4ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 57  ORDER BY "users"."id" ASC LIMIT 1
  FamilyTree Load (1.0ms)  SELECT  "family_trees".* FROM "family_trees"  WHERE "family_trees"."user_id" = $1 LIMIT 1  [["user_id", 57]]
   (1.2ms)  SELECT COUNT(*) FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 57]]
  Membership Load (1.4ms)  SELECT "memberships".* FROM "memberships"  WHERE "memberships"."user_id" = 57 AND "memberships"."family_tree_id" = 57
  Video Load (0.9ms)  SELECT  "videos".* FROM "videos"  WHERE "videos"."id" = $1 LIMIT 1  [["id", 172]]
   (0.9ms)  BEGIN
  SQL (1.3ms)  UPDATE "videos" SET "is_complete" = $1, "updated_at" = $2, "yt_video_id" = $3 WHERE "videos"."id" = 172  [["is_complete", "t"], ["updated_at", "2015-03-20 18:39:19.959122"], ["yt_video_id", "bMaCxSIbJYU"]]
   (1.5ms)  COMMIT
   (0.9ms)  BEGIN
  SQL (5.4ms)  INSERT INTO "nodes" ("created_at", "family_tree_id", "media_id", "media_type", "name", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id"  [["created_at", "2015-03-20 18:39:19.967237"], ["family_tree_id", 57], ["media_id", 172], ["media_type", "Video"], ["name", "Outro 10PP"], ["updated_at", "2015-03-20 18:39:19.967237"], ["user_id", 57]]
   (1.2ms)  COMMIT
  ActsAsTaggableOn::Tag Load (1.7ms)  SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = $1 AND "taggings"."taggable_type" = $2 AND "taggings"."context" = 'user_tags'  [["taggable_id", 45], ["taggable_type", "Node"]]
  Rendered videos/_tag_users_in_video.html.erb (10.3ms)
  Rendered videos/tag_users.js.erb (12.7ms)

编辑 5

没有向save_video 发送请求的前端部分。发生的情况是,用户填写了出现在此模式中的表单:

<div id="overlay">&nbsp;</div>
<div class="popup" id="add-video-step-4" data-step="4" data-intro="GETS TO UPLOADING">
  <div class="titles clearfix">
      <h2>Upload a Video</h2>
      <p><i>Step 1 of 3</i></p>
  </div>
  <div class="content">
    <% if @family_tree %>
      <%= simple_form_for([@family_tree, @video], :remote => true) do |f| %>
        <div class="column">
              <div class="f-row">
                  <%= f.input :title, label: "Title:" %>
              </div>
              <div class="f-row">
                  <%= f.input :description,label: "Description:" %>
              </div>
              <div class="f-row">
                  <%= f.input :circa, as: :datepicker, start_year: Date.today.year - 5, label: "Circa:" %>
              </div>
              <div class="f-row">
                  <label for="family">Family in this video:</label>
                  <%= f.collection_select :user_ids, @family_tree.members.order(:first_name), :id, :first_name, {}, {multiple: true} %>
              </div>
          </div>
          <%= f.button :submit, "Add Video", id: "video-submit" %>
        <% end %>
      <% end %>
    </div> <!-- //content -->
</div> <!-- //popup -->

然后,该模式将请求发送到我的 Video 控制器中的 Create 操作:

  def create
    authorize! :read, @family_tree
    @video = Video.new(video_params)

    respond_to do |format|
      if @video.save
        format.html { redirect_to video_upload_path(@video) }
        # format.json { render action: 'show', status: :created, location: @video }
      else
        format.html { render action: 'new' }
        format.json { render json: @video.errors, status: :unprocessable_entity }
      end
    end
  end

如果成功,则将请求发送到此Video#Upload 操作:

  def upload
    authorize! :read, @family_tree

    @video = Video.find(params[:video_id])
    @upload_info = Video.token_form(@video, video_save_video_url(@video))

    respond_to do |format|
        ## Note that I have been tinkering with this, but it doesn't work properly yet
        format.html { redirect_to video_tag_users_path(@video, @node) } 
        format.js
    end
  end

首先发送到赋值语句中的video_save

希望能提供清晰的说明。

编辑 6

这是我application.js的内容

//= require jquery
//= require jquery_ujs
//= require best_in_place
//= require bootstrap-sprockets
//= require jquery-ui/datepicker
//= require best_in_place.jquery-ui
//= require jquery.purr
//= require best_in_place.purr
//= require bootstrap.file-input
//= require chosen.jquery
//= require main.js
//= require spin.min
//= require ladda.min
//= require masonry.js
//= require introjs
//= require pnotify

$(document).ready(function(){   
    $("input.datepicker").datepicker();
      /* Activating Best In Place && Include Success Highlighting & Bounce for comments & videos */
        $(".best_in_place").best_in_place().bind("ajax:success", function () {$(this).closest('p, h5').effect('highlight').effect("bounce", { times:3 },  { duration:400}).dequeue(); });
        $('.dropdown-toggle').dropdown();       
      $('#unread-notification').click(function(){
        var url = $(this).data('read-url');
        $.ajax({
          type: "PUT",
          url: url
        });
      });   
});

编辑 7

这是调用第一个create 后的服务器日志:

Started POST "/family_trees/57/videos" for 127.0.0.1 at 2015-03-23 15:05:46 -0500
Processing by VideosController#create as JS
  Parameters: {"utf8"=>"✓", "video"=>{"title"=>"Hello There", "description"=>"This is an interesting video", "circa"=>"", "user_ids"=>[""]}, "commit"=>"Add Video", "family_tree_id"=>"57"}
  User Load (15.9ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 57  ORDER BY "users"."id" ASC LIMIT 1
  FamilyTree Load (5.6ms)  SELECT  "family_trees".* FROM "family_trees"  WHERE "family_trees"."user_id" = $1 LIMIT 1  [["user_id", 57]]
  FamilyTree Load (2.2ms)  SELECT  "family_trees".* FROM "family_trees"  WHERE "family_trees"."id" = $1 LIMIT 1  [["id", 57]]
   (2.3ms)  SELECT COUNT(*) FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 57]]
  Membership Load (1.8ms)  SELECT "memberships".* FROM "memberships"  WHERE "memberships"."user_id" = 57 AND "memberships"."family_tree_id" = 57
   (2.6ms)  BEGIN
  SQL (6.1ms)  INSERT INTO "videos" ("created_at", "description", "title", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["created_at", "2015-03-23 20:05:46.637067"], ["description", "This is an interesting video"], ["title", "Hello There"], ["updated_at", "2015-03-23 20:05:46.637067"]]
   (2.8ms)  COMMIT
Redirected to http://localhost:3000/videos/177/upload
Completed 302 Found in 84ms (ActiveRecord: 39.2ms)


Started GET "/videos/177/upload" for 127.0.0.1 at 2015-03-23 15:05:46 -0500
Processing by VideosController#upload as JS
  Parameters: {"video_id"=>"177"}
  User Load (2.6ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 57  ORDER BY "users"."id" ASC LIMIT 1
  FamilyTree Load (1.9ms)  SELECT  "family_trees".* FROM "family_trees"  WHERE "family_trees"."user_id" = $1 LIMIT 1  [["user_id", 57]]
   (1.3ms)  SELECT COUNT(*) FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 57]]
  Membership Load (1.7ms)  SELECT "memberships".* FROM "memberships"  WHERE "memberships"."user_id" = 57 AND "memberships"."family_tree_id" = 57
  Video Load (2.8ms)  SELECT  "videos".* FROM "videos"  WHERE "videos"."id" = $1 LIMIT 1  [["id", 177]]
  Rendered videos/_upload_video.html.erb (4.6ms)
  Rendered videos/upload.js.erb (7.6ms)
Completed 200 OK in 344ms (Views: 23.7ms | ActiveRecord: 10.3ms)

编辑 8

_upload_video.html.erb

<div class="bootstrap-styles" id="add-video-step-3"> 
 <div class="modal-header">
      <div class="titles clearfix">
          <h2>Upload a Video</h2>
          <p><i>Step 2 of 3</i></p>
      </div>
  </div>
  <div class="modal-body">
    <div class="content">
      <%= form_tag @upload_info[:url], :multipart => true do %>
        <%= hidden_field_tag :token, @upload_info[:token] %>
        <div class="uploader clearfix">
                        <%= file_field_tag :file, title: 'SELECT FILE TO UPLOAD', class: "upload" %>
        </div>
        <button class="btn btn-success ladda-button" data-color="green" data-style="expand-left"><span class="ladda-label">Upload Video</span><span class="ladda-spinner"></span></button>
      <% end %>

    </div>
  </div>
  <div class="modal-footer">
  </div>
</div>

upload.js.erb

$("#add-video-step-4").html("<%= escape_javascript(render 'videos/upload_video') %>");

【问题讨论】:

  • 您有一个respond_to 部分,可将您的回复重定向到render.html
  • 那么我应该从该块中删除format.html 吗?
  • 将其替换为渲染render 'tag_users.js'
  • 我的意思是整个 respond_to
  • 如果你想保存视频并渲染弹出窗口,那么你应该按照我说的去做 - 在 save_video 操作中渲染你的 js 而不是重定向

标签: javascript jquery ruby-on-rails ruby-on-rails-4


【解决方案1】:

假设这是你的代码

 def tag_users
    authorize! :read, @family_tree
    @video = Video.find(params[:video_id])
    @node = @video.node

    respond_to do |format|
      render format.html
      format.js
    end
  end

而且,通过查看输出,我可以说服务器正在接收HTML 作为格式。因为,你想执行script,你必须将datatype发送到script

查看 html 代码,我认为您必须将 data: {type: "script"} 传递给 simple_form 函数,所以它将是

<div id="overlay">&nbsp;</div>
<div class="popup" id="add-video-step-4" data-step="4" data-intro="GETS TO UPLOADING">
  <div class="titles clearfix">
      <h2>Upload a Video</h2>
      <p><i>Step 1 of 3</i></p>
  </div>
  <div class="content">
    <% if @family_tree %>
      <%= simple_form_for([@family_tree, @video], :remote => true,  data: {type: "script"} ) do |f| %>
        <div class="column">
              <div class="f-row">
                  <%= f.input :title, label: "Title:" %>
              </div>
              <div class="f-row">
                  <%= f.input :description,label: "Description:" %>
              </div>
              <div class="f-row">
                  <%= f.input :circa, as: :datepicker, start_year: Date.today.year - 5, label: "Circa:" %>
              </div>
              <div class="f-row">
                  <label for="family">Family in this video:</label>
                  <%= f.collection_select :user_ids, @family_tree.members.order(:first_name), :id, :first_name, {}, {multiple: true} %>
              </div>
          </div>
          <%= f.button :submit, "Add Video", id: "video-submit" %>
        <% end %>
      <% end %>
    </div> <!-- //content -->
</div> <!-- //popup -->

看这里Why I need add "data: {type: "script"}" on remote link with rails / ajax

【讨论】:

  • 我试过这个,但我得到了错误:ActionController::UnknownFormatrespond_to dotag_users 中的行。
  • 你能给我看看输出吗?此外,我从您的控制器中删除了代码的最后一行,该代码重定向到某个路径。
  • 现在我得到一个缺少模板的错误...具体来说:ActionView::MissingTemplate at /videos/177/save_video Missing template videos/save_video, application/save_video with {:locale=&gt;[:en], :formats=&gt;[:html], :variants=&gt;[], :handlers=&gt;[:erb, :builder, :raw, :ruby, :coffee, :jbuilder, :haml]}.
【解决方案2】:

如果您想使用重定向,您可以尝试在重定向路径中添加格式:

format.html { redirect_to video_tag_users_path(@video, format: :js) }

【讨论】:

  • 不幸的是,这也不起作用:(它只是将 RAW HTML 输出到屏幕上,而不执行 HTML。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多