I’m using jquery to render a like button on a story. I have two models story and like
Here’s the likes controller code:
def create
@like = Like.new(params[:like])
@story = Story.find(params[:story])
@like.story = @story
if @like.save
respond_to do |format|
format.html
format.js
end
end
end
def destroy
@like = Like.find(params[:id])
#@story = @like.story
@like.destroy
respond_to do |format|
format.html { redirect_to stories_url }
format.js
format.json { head :ok }
end
end
This is the button partial (stories/like_button):
<% unless user_likes_story?(@story, current_user) %>
<%= button_to 'like', "/likes?story=#{@story.id}", :id => 'like_button', :remote => true %>
<% else %>
<%= button_to 'liked', @liked, :class => 'like_button unlike', :id => 'unlike_button', :remote => true, method: :delete %>
<% end %>
The problem is that my create.js.erb, when rendering the ‘unlike’ button, doesn’t properly load the @liked instance variable, because it’s being set in the #show action of the stories controller before the user has liked the story, so I can’t figure out how or where to set it so the JS will render the unlike properly. I’m probably making this harder than it has to be, but…
create.js.erb
$('.button_to').replaceWith('<%=j render 'stories/like_button' %>');
$('#story_likes_count').replaceWith('<%=j render 'stories/likes_count' %>');
Here’s how I tried setting @liked, in stories#show
def show
@like = Like.new
@story = Story.find(params[:id])
if current_user
@liked = Like.find_by_user_id_and_story_id(current_user,@story)
end
respond_to do |format|
format.html # show.html.erb
format.json { render json: @story }
end
end
Any idea how to do this properly? Should I just move the partial out of the stories folder?
The solution was pretty simple. In the controller, doing this:
Passes the variable and makes it available to the partial when it’s rendered.