繁体   English   中英

我如何呈现我的 JS erb?

[英]How do I render my JS erb?

我有一个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

因此,我将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部分中吐出 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操作中的save_video 这是代码:

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

结果如下:

渲染的 JS

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

原始模态我试图让它看起来像

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

假设这是你的代码

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

请参阅此处为什么我需要在带有 rails / ajax 的远程链接上添加“数据:{type:“script”}”

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM