3

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

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

意见/订阅/create.js.erb

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

意见/订阅/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

意见/共享/_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 -> posts

4

1 回答 1

3

看起来您在“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​​ 环境,所以我无法验证这是否可以解决您的问题,但我认为它应该让您朝着正确的方向前进。

于 2012-07-20T19:22:52.460 回答