用jquery和locals渲染

时间:2018-04-24 10:46:35

标签: ruby-on-rails ruby-on-rails-5

我无法使用jquery渲染,我有一个显示所有通知的通知页面,然后当我点击1时,它会显示所有的1,如果我点击2,它将显示所有的2等等。

这是开始呈现所有通知的地方。当地人在这里工作正常。

<% @notifications.each do |x| %>
  <div class="testing123">
    <%= render 'notification', x: x %>
  </div>
<% end %>

然后我点击链接进行更改 这是控制器

def index
  if params[:type]
    @notifications = Notification.where(notification_type: params[:type])
  else
    @notifications = Notification.all
  end
    respond_to do |format|
      format.html
      format.js{
        render 'notifications/jserb/select_notifications'
      }
  end
end

然后到达这里:

$('.testing123').empty();
$("<%= escape_javascript(render @notifications, :locals => {:x => x}) %>").appendTo(".testing123");

但我一直收到这个错误  ActionView::Template::Error (undefined local variable or method x' for #<#<Class:0x007fae10882ed8>:0x007fae0f6234b8>):

EDIT-1:这是我点击链接的地方:

<%= link_to "likes", notifications_path, remote: true %>

EDIT-2:这是通知:

<div class="notification-body flerowspb" id="body<%=x.id%>">
  <div class="flerowspb" style="width:80%">
    <div class="notif-check flecolcen">
      <%= check_box_tag "read_notif[]", value="#{x.id}", checked = false, options = {class: 'checked-id', id: "check-#{x.id}"} %>
    </div>
    <div class="notif-details ">
      <div class="notif-time flerowspb">
        <% if !x.viewed %>
           <span class="glow" id="glow-<%=x.id%>"> New  <%= x.notification_type.capitalize %></span>
        <% else %>
           <span><span class="text-grey"> New <%= x.notification_type.capitalize %></span></span>
         <% end %>
         <span class="text-grey font-small"> <%= time_ago_in_words(x.created_at) %> ago</span>
      </div>
      <div class="notif-body font-medium text-grey">
        You have <%= x.status_count %> <%= x.title %>  <br>
        Click <span class="text-blue"><%= link_to "Here", entry_path(x.entry_id, notification_id: x.id) %> </span> to view it
      </div>
    </div>
  </div>
  <div class="notif-image">
    <%= image_tag x.entry.image.small_thumb %>
  </div>
</div>

EDIT-3:这是我得到的完整错误:

ActionView::Template::Error (undefined local variable or method `x' for #<#<Class:0x007fae0e6f32b8>:0x007fae11ac1838>):
1: <div class="notification-body flerowspb" id="body<%=x.id%>">
2:   <div class="flerowspb" style="width:80%">
3:     <div class="notif-check flecolcen">
4:       <%= check_box_tag "read_notif[]", value="#{x.id}", checked = false, options = {class: 'checked-id', id: "check-#{x.id}"} %>

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

您的代码问题是在点击链接后点击通知操作以及您获得@notifications作为通知数组的位置,因此在js.erb之后您正在渲染附加部分{{1使用局部变量notification.html.erb,但在您的控制器中,您将获得x变量,

这应该是这样的: 在@notifications

notifications/_notification.html.erb

并在<div class="testing123"> <% notifications.each do |x| %> <%#= render 'notification', x: x %> #... <% end %> </div>

notification.js.erb