问题
I just want to do a rails action without a view.
In my 'routes.rb'
resources :pictures do
member do
post 'dislike'
end
end
In my 'PictureController.rb'
this does not work
def dislike
@picture = Picture.find(params[:id])
@like = Like.find(:user_id => current_user.id, :picture_id => params[:id])
@like.destroy
respond_to do |format|
format.html { render :action => :show, :id => params[:id], notice: 'You don\'t like this picture anymore.' }
format.json { render json: @picture }
end
end
neither do this
def dislike
@picture = Picture.find(params[:id])
@like = Like.find(:user_id => current_user.id, :picture_id => params[:id])
@like.destroy
respond_to do |format|
format.html { redirect_to @picture, notice: 'You don\'t like this picture anymore.' }
format.json { render json: @picture }
end
end
or even this (but this is not the case for me, i want a feedback to the user via json and via html)
def dislike
@picture = Picture.find(params[:id])
@like = Like.find(:user_id => current_user.id, :picture_id => params[:id])
@like.destroy
render :nothing => true
end
But i keep getting this error message:
ActionView::MissingTemplate: Missing template pictures/dislike, application/like with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :coffee]}.
How should i tell rails that this action in PicturesController does not needs a view?
Solved!
I didn't really solved the problem of telling rails i did not need a view, i just created another controller, put the method in it, and told rails routing to match the dislike action with a match
call.
I cannot tell for sure, but i think it was a problem with the resources :picture
in my routes.rb
file...
But anyway, thank you guys! =)
回答1:
Something like this?
def dislike
@picture = Picture.find(params[:id]
@like = Like.find(:user_id => current_user.id, :picture_id => params[:id])
@like.destroy
render :nothing => true
end
回答2:
Just created another controller with the dislike action:
def dislike
@picture = Picture.find(params[:id])
@like = Like.find(:user_id => current_user.id, :picture_id => params[:id])
@like.destroy
respond_to do |format|
format.html { redirect_to :back, notice: 'You don\'t like this picture anymore.' }
format.json { render json: @picture }
end
end
and modified my routes.rb to match this action:
match 'pictures/:id/dislike' => "likes#dislike", :via => :post
and my link to dislike now is
<%= link_to 'Dislike!', {:action => :dislike, :controller => :likes}, :method => :post %>
回答3:
Most likely, the problem is that you're hitting this action via an ajax request. So the controller is looking for format.js
, but you haven't specified a response for that format in your block. Thus it's falling through to the default.
Try
format.js { render json: @picture }
You may also need to tell the ajax request to expect a json response.
来源:https://stackoverflow.com/questions/12919631/rails-controller-action-without-a-view