【问题标题】:Rails 3 javascript: How to render a partial with parametersRails 3 javascript:如何使用参数渲染部分
【发布时间】:2023-09-10 03:29:01
【问题描述】:

我仍然掌握 Rails 的窍门。这里我使用的是 Rails 3,目标基本上是当我单击订阅按钮时触发 AJAX 调用,post_form 部分呈现在我刚刚订阅的主题的下方。然后该按钮变为取消订阅按钮,并且 post_form 部分被删除。按钮的切换单独起作用(即:通过删除紧跟在 sn-ps 之后的两个中的第二行),但 *post_form* 部分的呈现不起作用。

问题是我似乎无法在以下两个部分中获得正确的语法和/或参数传递。只是没有传递主题对象,单击订阅或取消订阅按钮时,我收到 NilClass 错误的无效模型名称。如果我手动刷新页面,部分会以正确的方式呈现或隐藏,因此实际上只是 AJAX 部分无法正常工作。

views/subscription/create.js.erb

$("#subscription_form").html("<%= escape_javascript(render('users/unsubscribe')) %>");
$("#post_form").html("<%= escape_javascript(render('shared/post_form', :topic => @topic)) %>");

views/subscription/destroy.js.erb

$("#subscription_form").html("<%= escape_javascript(render('users/subscribe')) %>");
$("#post_form").html("<%= escape_javascript(render('shared/post_form', :topic => @topic)) %>");

视图/用户/_subscription_form.html.erb

<% unless current_user?(@user) %>
  <div id="subscription_form">
  <% if current_user.subscribed?(@topic) %>
    <%= render 'users/unsubscribe', :topic => @topic %>
  <% else %>
    <%= render 'users/subscribe', :topic => @topic %>
  <% end %>
  </div>
<% end %>

控制器/订阅控制器.rb

class SubscriptionsController < ApplicationController
      before_filter :signed_in_user

      respond_to :html, :js

      def create
        @topic = Topic.find(params[:subscription][:topic_id])
        current_user.subscribe!(@topic)
        respond_with @topic
      end

      def destroy
        @topic = Subscription.find(params[:id]).topic
        current_user.unsubscribe!(@topic)
        respond_with @topic
      end
   end

views/shared/_post_form.html.erb

<%= form_for(@post) do |f| %>
  <div class="field">
    <%= f.hidden_field :topic_id, :value => @topic.id %>
    <%= f.text_area :content, placeholder: "Tell us about it ..." %>
  </div>
  <%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>

如果有任何帮助,关系是:

post -> belongs_to -> 主题和主题 -> has_many -> 帖子

【问题讨论】:

  • 你做“respond_with @topic”有什么原因吗?您应该可以省略这些行,因为您已经按照惯例命名了您的视图。

标签: javascript ruby-on-rails-3


【解决方案1】:

看起来您在“views/_post_form.html.erb”文件中使用了变量“@post”。

<%= form_for(@post) do |f| %>

由于您没有在操作中的任何位置设置该变量,您将收到空引用错误。

你需要做这样的事情:

def create
  @post = Post.find(the_post_id)
  @topic = Topic.find(params[:subscription][:topic_id])
  current_user.subscribe!(@topic)
  respond_with @topic
end

此外,您将“主题”变量作为本地变量传递,但将其作为实例变量访问。您应该将 _post_form.html.erb 文件更改为如下所示:

<%= form_for(@post) do |f| %>
  <div class="field">
    <%= f.hidden_field :topic_id, :value => topic.id %>
    <%= f.text_area :content, placeholder: "Tell us about it ..." %>
  </div>
  <%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>

我没有现成的 ruby​​ 环境,因此我无法验证这是否会解决您的问题,但我认为它应该会让您朝着正确的方向前进。

【讨论】:

  • 环境与否,你搞定了。谢谢。