I'm still getting the hang of Rails. Here I'm using Rails 3 and the goal basically is to have an AJAX call triggered when I click the subscribe button the post_form partial is rendered beneath for the topic I have just subscribed to. The button then becomes an unsubscibe button and the post_form partial is removed. The toggling of the button alone works (i.e: by removing the second line in the two immediately following snippets), but the rendering of the *post_form* partial does not.
The problem is I can't seem to get the right syntax and/or passing of parameters in the two following partials. The topic object is just not passed and I get an invalid model_name for NilClass error when clicking on the subscribe or unsubscribe button. If I refresh the page manually, the partial is rendered or hidden the correct way, so it's really just the AJAX part that isn't working right.
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)) %>");
views/users/_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 %>
controllers/subscriptions_controller.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 %>
If it is of any help, the relationships are:
post -> belongs_to -> topic and topic -> has_many -> posts