在Rails 4中用AJAX替换部分:没有错误,没有更新的数据

时间:2016-10-07 12:37:00

标签: jquery ruby-on-rails ajax

对于以下内容,我没有收到任何错误,并且在执行like_oneliner方法后我的list-partial再次被加载。但是未更改的数据(oneliner.users.countif/else !joined(oneliner)未刷新)未显示。

我正在尝试使用upvote和downvote更改按钮类,并尝试使用内置的AJAX功能。

模型/ campaign.rb

belongs_to :user
has_many :oneliners
has_many :general_connections

模型/ oneliner.rb

has_many :general_connections
has_many :users, through: :general_connections
belongs_to :campaign

模型/ general_connection.rb

belongs_to :oneliner
belongs_to :user
belongs_to :campaign

模型/ user.rb

has_many :general_connections
has_many :oneliners, through: :general_connections
has_many :campaigns

控制器/ general_connection.rb

def like_oneliner
  @oneliner = Oneliner.find(params[:oneliner_id])
  current_user.general_connections.create(oneliner: @oneliner)
  respond_to do |format|
    format.html { redirect_to :back }
    format.js
  end
end

def unlike_oneliner
  @general_connection = GeneralConnection.where("oneliner_id = ? AND user_id = ?", params[:oneliner_id], current_user.id).first
  @oneliner = @general_connection.oneliner

  @general_connection.destroy
  respond_to do |format|
    format.html { redirect_to :back }
    format.js
  end
end

视图/活动/ show.html.erb

<div class="row">
    <ul class="collection">
        <% @oneliners.each do |oneliner| %> 
            <%= render partial: 'oneliners/list', locals: { oneliner: oneliner } %>
        <% end %>
    </ul>
</div>

视图/ oneliners / _list.html.erb

<li class="collection-item avatar">
  <i class="circle black"><%= oneliner.users.count %></i>
  <span class="title"><%= oneliner.title %></span>
  <p><%= timeago_tag oneliner.created_at, :nojs => true, :limit => 100.days.ago %> / <%=t 'list.employee' %><%= oneliner.user.name %>
  </p>

  <% if !joined(oneliner) %>
    <%= form_tag(onelinerlike_path, remote: true) do %>
      <%= hidden_field_tag 'oneliner_id', oneliner.id %>
        <%= button_tag 'thumb_up', id: "#{ dom_id(oneliner) }", class: "secondary-content material-icons grey-text", style: "background-color:white;border:none;" %>
    <% end %>
  <% else %>
    <%= form_tag(onelinerunlike_path, remote: true) do %>
      <%= hidden_field_tag 'oneliner_id', oneliner.id %>
      <%= button_tag 'thumb_up', id: "#{ dom_id(oneliner) }", class: "secondary-content material-icons orange-text", style: "background-color:white;border:none;" %>
    <% end %>
  <% end %>
</li>

视图/ general_connection / like_oneliner.js.erb

$('#<%= dom_id(@oneliner) %>').replaceWith(<%= j render partial: 'oneliners/list', locals: {oneliner: @oneliner} %>");

类似和不同的方法确实有效,我看到Timeago字符串中的一个小变化(例如2 months中的2 months ago更改),但就是这样。 oneliner.users.count if/else !joined(oneliner)仅在刷新页面时显示新数据。

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

$('#<%= dom_id(@oneliner) %>')这会给你一个要替换的按钮元素。您应该通过指定它的id / class来替换整个partial。