我如何渲染我的JS erb?

时间:2015-03-20 13:44:21

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

我在save_video上执行了NodesController操作:

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

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

render 'tag_users.js'  

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

即。这是我的浏览器中显示的内容,它会重定向到网址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部分吐出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

这就是结果:

Rendered JS

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

Original Modal I am trying to get it to look like

编辑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 -->

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

  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') %>");

2 个答案:

答案 0 :(得分:0)

假设这是你的代码

 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

答案 1 :(得分:0)

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

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