Rails 4:使用AJAX调用更新模型属性

时间:2015-11-20 18:23:57

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

这是关于Rails 4: custom action to update only one param with AJAXRails 4: select DOM element with dynamically generated id的后续问题。

我无法弄清楚如何根据我得到的好答案让事情发挥作用,所以我想从一个空白的平板开始。 < / p>

在我的Rails 4应用中,我有一个Calendar和一个Post模型,设置了浅路线:

resources :calendars do
  resources :posts, shallow: true
end

日历has_many帖子和帖子belong_to日历。

在日历show.html.erb视图中,我会显示属于日历的所有帖子。

从此日历show.html.erb视图中,我需要使用AJAX调用更新帖子的:approval param,以便只刷新与此特定帖子的批准相关的DOM元素,而不是整页。

这是日历show.html.erb中代码的一部分,可让我更新帖子的:approval

<tr id="post_row_<%= post.id%>"> 
  [...]  # Truncated for brivety 
  <td class="cell_content_center post_approval_section">
    <% if post.approval == "ok" %>
      <span class="ok_green">
    <% else %>
      <span class="approval_blue" %>
    <% end %>
      <%= link_to post_path(:id => post.id, "post[approval]" => "ok", approval_update: true), remote: true, :method => :patch do %>
        <span class="glyphicon glyphicon-ok" data-toggle="tooltip" data-placement="left" title="Approve Post"></span>
      <% end %>
    </span><br/>
    <% if post.approval == "edit" %>
      <span class="edit_yellow">
    <% else %>
      <span class="approval_blue" %>
    <% end %>
      <%= link_to post_path(:id => post.id, "post[approval]" => "edit", approval_update: true), remote: true, :method => :patch do %>
      <span class="glyphicon glyphicon-repeat" data-toggle="tooltip" data-placement="left" title="Require Edits"></span>
    <% end %>
    </span><br/>
    <% if post.approval == "remove" %>
      <span class="remove_red">
    <% else %>
      <span class="approval_blue" %>
    <% end %>
      <%= link_to post_path(:id => post.id, "post[approval]" => "remove", approval_update: true), remote: true, :method => :patch do %>
      <span class="glyphicon glyphicon-remove" data-toggle="tooltip" data-placement="left" title="To Be Deleted"></span>
    <% end %>
    </span>
  </td>
  [...]  # Truncated for brivety
</tr>

然后,在posts_controller.rb

def update
    if params["approval_update"]
      respond_to do |format|
        if @post.update(post_params)
          format.js { render :action => "update_post_approval" }
        else
          format.html { redirect_to :back }
        end
      end
    else
      respond_to do |format|
        if @post.update(post_params)
          format.html { redirect_to post_path(@post) }
          format.json { render :show, status: :ok, location: @post }
          format.js
        else
          format.html { render :edit }
          format.json { render json: @post.errors, status: :unprocessable_entity }
        end
      end
    end
  end

  def update_post_approval
    respond_to do |format|
      format.js
    end
  end

注意: 在这里,我无法使用默认的Posts#Update操作,因为它已被另一个AJAX调用用于更新:approval帖子show.html.erb视图中的参数,这就是我们呈现update_post_approval自定义操作的原因。

然后,我有以下app/views/posts/update_post_approval.js.erb文件:

$("tr#post_row_#{post.id} > td.post_approval_section").html('<%= j render(partial: "calendars/post_approval") %>');

最后,我有以下calendars/_post_approval.html.erb部分:

<td class="cell_content_center post_approval_section">
  <% if post.approval == "ok" %>
    <span class="ok_green">
  <% else %>
    <span class="approval_blue" %>
  <% end %>
    <%= link_to post_path(:id => post.id, "post[approval]" => "ok", approval_update: true), remote: true, :method => :patch do %>
      <span class="glyphicon glyphicon-ok" data-toggle="tooltip" data-placement="left" title="Approve Post"></span>
    <% end %>
  </span><br/>
  <% if post.approval == "edit" %>
    <span class="edit_yellow">
  <% else %>
    <span class="approval_blue" %>
  <% end %>
    <%= link_to post_path(:id => post.id, "post[approval]" => "edit", approval_update: true), remote: true, :method => :patch do %>
    <span class="glyphicon glyphicon-repeat" data-toggle="tooltip" data-placement="left" title="Require Edits"></span>
  <% end %>
  </span><br/>
  <% if post.approval == "remove" %>
    <span class="remove_red">
  <% else %>
    <span class="approval_blue" %>
  <% end %>
    <%= link_to post_path(:id => post.id, "post[approval]" => "remove", approval_update: true), remote: true, :method => :patch do %>
    <span class="glyphicon glyphicon-remove" data-toggle="tooltip" data-placement="left" title="To Be Deleted"></span>
  <% end %>
  </span>
</td>

当我点击<td class="cell_content_center post_approval_section">部分中的三个链接之一来更新帖子:approval参数时,实际更新了参数,我们可以在服务器日志中看到:

Started PATCH "/posts/38?approval_update=true&post%5Bapproval%5D=ok" for ::1 at 2015-11-20 08:03:50 -0800
Processing by PostsController#update as JS
  Parameters: {"approval_update"=>"true", "post"=>{"approval"=>"ok"}, "id"=>"38"}
  User Load (1.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
  Post Load (0.7ms)  SELECT  "posts".* FROM "posts" WHERE "posts"."id" = $1 LIMIT 1  [["id", 38]]
   (0.6ms)  BEGIN
  SQL (1.1ms)  UPDATE "posts" SET "approval" = $1, "updated_at" = $2 WHERE "posts"."id" = $3  [["approval", "ok"], ["updated_at", "2015-11-20 16:03:50.888587"], ["id", 38]]
  SQL (1.3ms)  INSERT INTO "versions" ("event", "object", "whodunnit", "created_at", "object_changes", "item_id", "item_type") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id"  [["event", "update"], ["object", "---\nid: 38\ncalendar_id: 6\ndate: 2015-11-17 22:09:00.000000000 Z\nsubject: Subject\nformat: Link\ncopy: https://www.wid.la/\ncreated_at: 2015-11-17 22:09:28.713416000 Z\nupdated_at: 2015-11-20 16:03:20.613597000 Z\nimage_file_name: \nimage_content_type: \nimage_file_size: \nimage_updated_at: \nshort_copy: ''\nscore: \nfacebook: true\ntwitter: false\ninstagram: false\npinterest: false\ngoogle: false\nlinkedin: false\ntumblr: \nsnapchat: \napproval: remove\n"], ["whodunnit", "1"], ["created_at", "2015-11-20 16:03:50.888587"], ["object_changes", "---\napproval:\n- remove\n- ok\nupdated_at:\n- 2015-11-20 16:03:20.613597000 Z\n- 2015-11-20 16:03:50.888587000 Z\n"], ["item_id", 38], ["item_type", "Post"]]
   (1.6ms)  COMMIT
  Rendered calendars/_post_approval.html.erb (0.1ms)
  Rendered posts/update_post_approval.js.erb (1.5ms)
Completed 200 OK in 27ms (Views: 9.9ms | ActiveRecord: 6.3ms)

但是,除非我手动刷新页面,否则视图上没有任何变化。

我现在花了好几个小时来解决这个问题,并且无法弄清楚问题是由Ruby还是JS代码引起的。

如有必要,我很乐意分享更多代码。

知道我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

错误在于:

$(“tr#post_row_ #{post.id} &gt; td.post_approval_section”)。html('&lt;%= j render(partial:“calendars / post_approval”) )%&gt;');

<强>更新 它应该是:

$("tr#post_row_<%= @post.id %> > td.post_approval_section").html('<%= j render(partial: "calendars/post_approval", locals: {post: @post}) %>');