Adding a route for a controller action - ruby-on-rails

I am implementing a like system in my rails app using David Celis gem called Recommendable. I've gotten everything to work in the console but I can't get the right routes and I'm getting the "No route matches [GET] "/categories/1/posts/1/like" error.
I have the following in my models:
class Category < ActiveRecord::Base
has_many :posts, :dependent => :destroy
extend FriendlyId
friendly_id :name, use: :slugged
end
class Post < ActiveRecord::Base
belongs_to :category
end
In my Post Controller I have:
class PostsController < ApplicationController
before_filter :authenticate_user!
before_filter :get_category
def like
#post = Post.find(params[:id])
respond_to do |format|
if current_user.like #post
else
flash[:error] = "Something went wrong! Please try again."
redirect_to show_post_path(#category, #post)
end
end
end
end
In my routes I have:
resources :categories do
resources :posts do
put :like, :on => :member
end
end
match 'categories/:category_id/posts/:id', :to => 'posts#show', :as => 'show_post'
Can someone please point at my errors? I can get the PUT to work but I dont know where the GET error is coming from as I am trying to redirect back to the post if an error occurs when the user like's a certain post. Thank you in advance.
EDIT:
In my view I have:
- title "#{#post.class}"
%p#notice= notice
%p
%b Title:
= #post.title
%p
%b Description:
= #post.description
%p
%b Likes:
= #post.liked_by.count
= link_to 'Edit', edit_category_post_path(#post)
\|
= link_to 'Back', category_posts_path
\|
= link_to 'Like', like_category_post_path(#post)

Replace:
= link_to 'Like', like_category_post_path(#post)
with:
= link_to 'Like', like_category_post_path(#category, #post), method: :put
Or, as I like it:
= link_to 'Like', [#category, #post], method: :put
I think your like has to be:
def like
#post = Post.find(params[:id])
respond_to do |format|
format.html do
if current_user.like #post
flash[:notice] = "It's ok, you liked it!"
redirect_to :back
else
flash[:error] = "Something went wrong! Please try again."
redirect_to show_post_path(#category, #post)
end
end
end
end

Your route expects a PUT request, while you're issuing a GET request.
You'll need to either access your route via a button_to with :method => :put so that your app is issuing PUT requests (the correct solution), or change your route to use GET requests (the wrong way to make requests which modify state):
get :like, :on => :member

Related

ROR5: 'param is missing or the value is empty' error with adding Bookmarks

I have an app where users can ask questions and bookmark certain questions. I'm done with the users, questions, and answers, so I've added a BookmarkController & Bookmarks model. At first, I considered using associations, but my app has a few associations already so I'm (or I've attempted at) using query parameters such as user_id and question_id to fetch bookmarks.
The structure is a bit like StackOverflow. A user navigates to a single question view and bookmarks it on that page. This creates a new bookmark model containing the user_id of current_user and the question_id. The user can go to his profile to view all the questions he bookmarked, fetched using his user_id. (Answers cannot be bookmarked. Only questions.)
I've been getting a 'param is missing or the value is empty: bookmark' error, although I have followed similar steps I did for my QuestionsController. It would be great if someone could help me out in identifying what's wrong/bad about my code!
rake routes (first part omitted)
bookmark_question PUT /questions/:id/bookmark(.:format) questions#bookmark
questions GET /questions(.:format) questions#index
POST /questions(.:format) questions#create
new_question GET /questions/new(.:format) questions#new
edit_question GET /questions/:id/edit(.:format) questions#edit
question GET /questions/:id(.:format) questions#show
PATCH /questions/:id(.:format) questions#update
PUT /questions/:id(.:format) questions#update
DELETE /questions/:id(.:format) questions#destroy
route.rb (excerpt)
# Questions
get '/questions/:id' => 'bookmarks#create'
show.html.erb (questions#show)
<% if current_user %>
<%= link_to "Bookmark", :controller => 'bookmarks', :action => 'create' %>
<% end %>
BookmarksController
class BookmarksController < ApplicationController
def new
#bookmark = Bookmark.new
end
def create
#question = Question.find(params[:id]) # when I delete this line, I get a new error - "undefined local variable 'params'"
#bookmark = Bookmark.new(bookmark_params)
#bookmark.user_id = current_user.id
#bookmark.question_id = #question.id
#bookmark.save
redirect_to #question
end
def destroy
end
private
def bookmark_params
params.require(:bookmark).permit(:user_id, :question_id)
end
end
Bookmark model
class Bookmark < ApplicationRecord
validates :user_id, presence: true
validates :question_id, presence: true
end
QuestionsController
(at the moment, contains no reference to Bookmarks. I thought so because I did the routing, but this might be where I'm going wrong)
class QuestionsController < ApplicationController
def index
#questions = Question.all
end
def show
#question = Question.find(params[:id])
#answers = Answer.all
# Delete only appears when no answers
#deletable = (current_user== User.find(#question.user_id)) && (#question.answers.all.size==0)
end
def new
#question = Question.new
end
def create
if logged_in?
#question = Question.new(question_params)
#question.user_id = current_user.id
#question.save
redirect_to #question
else
redirect_to login_path
end
end
def destroy
#question = Question.find(params[:id])
#question.destroy
redirect_to root_path
end
private
def question_params
params.require(:question).permit(:picture_url, :country, :educational_level, :topic)
end
end
profile index.html.erb (just for ref)
<% if (#bookmarks.count == 0) %>
///
<% else %>
<%= #bookmarks.each do |bookmark| %>
<!-- Show bookmark content here like Question.find(bookmark.question_id) etc -->
<% end %>
<% end %>
I have looked a the previous qns that have the same error as me. But they were all using associations. I hope to not use associations as the bookmark model only needs to keep a record of the user id and qn id.
UPDATE
So, referring to the answers given, I updated my erb to:
<% if logged_in? %>
<%= link_to "Bookmark", :controller => 'bookmarks', :action => 'create', bookmark: {user_id: current_user.id, question_id: #question.id} %>
<% end %>
hence specifying the controller and action (and the params) that need to be directed. But rails sends an error:
No route matches {:action=>"create", :bookmark=>{:user_id=>2, :question_id=>4}, :controller=>"bookmarks", :id=>"4"}
So I assume it was a routing problem. As Pavan suggested, I did consider nesting my resources, but the nesting is already one level deep, as such:
resources :questions do
resources :answers
end
And I reckon doing something like:
resources :questions do
resources :bookmarks # or resources :bookmarks, only: create
resources :answers
end
won't work. (And it didn't :( )
I'm not so sure how to get this routing problem fixed (tried Googling). Thanks.
param is missing or the value is empty: bookmark
The reason for the error is bookmark_params expects a :bookmark key to be present in the params hash, which in your case is missing since you are not passing any.
Change link_to like below:
<% if current_user %>
<%= link_to "Bookmark", :controller => 'bookmarks', :action => 'create', bookmark: {user_id: current_user.id, question_id: #question.id} %>
<% end %>
Also, the route get '/questions/:id' => 'bookmarks#create' isn't right and would conflict with this route question GET /questions/:id(.:format) questions#show. I would instead recommend building nested routes
resources :users do
resources :questions do
resources :bookmarks, only: [:create]
end
end
Update:
Along with the above, you should change #question = Question.find(params[:id]) to #question = Question.find(params[:bookmark][:question_id])
'param is missing or the value is empty: bookmark, this error means that, there is no bookmark key present in your params object, but you defined your bookmark_params to have one:
def bookmark_params
params.require(:bookmark).permit(:user_id, :question_id)
end
That's why it's throwing the above error message.
You should make sure you send the user_id and question_id key/value pairs under the bookmark key. Something like this:
bookmark: { user_id: 1, question_id: 2}.
So, your code should look something like this (adding the bookmark to params):
<%= link_to "Bookmark", :controller => 'bookmarks', :action => 'create', bookmark: {user_id: current_user.id, question_id: #question.id} %>

Rails button_to No route matches {:action=>"complete", :controller=>"dashboard", :name=>"Order"}

Please help i have tried my best. I really need your help.
So im trying to make a mark order as complete. Now it all works up to the button to mark order as complete. I ran a migration to add.
class AddCompleteToOrder < ActiveRecord::Migration
def change
add_column :orders, :complete, :boolean, default: false
end
end
Then i added a method the order.rb of
def complete!
update(complete: true)
end
Then routes.rb
resources :orders do
post "complete", to: "orders#complete", on: :member
end
Then this is the button
= button_to "Mark as complete", { action: "complete", id: #order.id }
But i dont have a #order.id
but a order does have a #order.name so i changed it to
= button_to "Mark as complete", { action: "complete", name: #order.name }
But then i get the error:
ActionController::UrlGenerationError in Dashboard#dadmin
Showing /Users/jacksharville/Desktop/dancer/app/views/dashboard/dadmin.html.haml where line #87 raised:
No route matches {:action=>"complete", :controller=>"dashboard", :name=>"Order"}
Extracted source (around line #87):
85
86
87
= link_to "Back to Dashboard", :back, :class => 'btn-danger btn'
= button_to "Mark as complete", { action: "complete", name: #order.name }
So clearly im doing the routes.rb wrong but i cant fix it. Please help. Any help greatly appreciated.
routes.rb (full file)
Rails.application.routes.draw do
mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
get 'home/index'
root 'home#index'
#pages
get '/why' => 'pages#why'
get '/trak' => 'pages#trak'
get '/contact' => 'pages#contact'
get '/mydms' => 'pages#mydms'
get '/air' => 'pages#air'
get '/ocean' => 'pages#ocean'
get '/road' => 'pages#road'
get '/courier' => 'pages#courier'
get 'fulfilment' => 'pages#fulfilment'
get 'express' => 'pages#express'
resources :dashboard
get 'dadmin' => 'dashboard#dadmin'
get 'myorders' => 'dashboard#myorders'
get 'label' => 'dashboard#label'
resources "contacts", only: [:new, :create]
devise_for :users
as :user do
get 'users/edit' => 'devise/registrations#edit', :as => 'edit_user_registration'
put 'users' => 'devise/registrations#update', :as => 'user_registration'
end
resources "orders"
get "/confirm" => "confirmations#show"
get 'dconfirmation' => 'orders#confirmation'
resources :orders do
post "complete", to: "orders#complete", on: :member
end
end
orders_controller.rb
class OrdersController < ApplicationController
before_filter :authenticate_user!
def new
#order = Order.new
end
def create
#order = current_user.orders.new(order_params)
#order.email = current_user.email
#order.name = current_user.name
#order.address_line_1 = current_user.address_line_1
#order.address_line_2 = current_user.address_line_2
#order.postcode = current_user.postcode
#order.city = current_user.city
#order.country = current_user.country
if #order.save
redirect_to dconfirmation_path
end
end
def order_params
params.require(:order).
permit(
:email,
:delivery_name,
:company_name,
:delivery_address1,
:delivery_address2,
:delivery_address3,
:delivery_city,
:delivery_postcode,
:delivery_country,
:phone,
:package_contents,
:description_content,
:restricted_items,
:terms_conditions,
:insurance,
:contents_value,
:cf_reference,
:reference_number
)
end
def show
#user = User.find(params[:id])
end
def confirmation
end
def complete!
order = Order.find(params[:id])
order.complete!
# handle response
end
end
dashboard_controller.rb
class DashboardController < ApplicationController
before_filter :authenticate_user!
def index
end
def admindashboard
(current_user.nil?) ? redirect_to(root_path) : (redirect_to(root_path) unless current_user.admin?)
end
def adminuser
(current_user.nil?) ? redirect_to(root_path) : (redirect_to(root_path) unless current_user.admin?)
end
def dadmin
(current_user.nil?) ? redirect_to(root_path) : (redirect_to(root_path) unless current_user.admin?)
# #order = Order.all
#order = Order.order("name").page(params[:page]).per(1)
end
def myorders
#order = current_user.orders.order("name").page(params[:page]).per(1)
end
def show
#user = User.find(params[:id])
end
def label
#order = current_user.orders.order("name").page(params[:page]).per(1)
end
def complete!
order = Order.find(params[:id])
order.complete!
# handle response
end
end
You can specify this additional option in the button_to tag :controller => "order", but the proper way to use button_to tag is to not create a separate hash for options. Instead use it as a button_to("Mark as complete", controller: "order", action: "complete", name: #order.name)
try this
button_to "Mark as complete", { controller: "orders", action: "complete", name: #order.name }, {method: :post}
This link can help: Routing Error - No route matches when using button_to with custom action
rake routes give me:
complete_order POST /order/:id/complete(.:format) orders#complete
You need to move the complete action from DashboardsController to OrdersController, which is where it is defined in the routes file.
Also, you can probably use:
= button_to "Mark as complete", complete_order_path(#order)
The controller action is looking for params[:order_id] so it can find the right order. I am not sure how orders are defined in your view, but you will need to pass an order object to the path.
If by any chance you defined a to_param method in Order class, which defines order's name rather than id as params, you will need to update the complete action to look for an order by name.
But my guess is that it is the default id. So passing the order object to the path should work.

No route matches [GET] "/book/list" part II: The Route Revenge of Rails

I am trying to follow this rails tutorial but I am having a lot of issues due to version mismatches. I followed the instructions exactly and I really understand everything up until now but I can't seem to resolve this routing issue on my own. I read a good deal about routes independently but can't figure out what to do. This question has been posted once before on stackoverflow but that solution does not work for me because of version issues
Error Message:
No route matches [GET] "/book/list"
When trying to access http://localhost:3000/book/list.
Code
route.rb
Rails.application.routes.draw do
resources: :books
end
views>book>list.rhtml
<% if #books.blank? %>
<p>There are not any books currently in the system.</p>
<% else %>
<p>These are the current books in our system</p>
<ul id="books">
<% #books.each do |c| %>
<li><%= link_to c.title, {:action => 'show', :id => c.id} -%></li>
<% end %>
</ul>
<% end %>
<p><%= link_to "Add new Book", {:action => 'new' }%></p>
models>book.rb
class Book < ActiveRecord::Base
belongs_to :subject
validates_presence_of :title
validates_numericality_of :price, :message=>"Error Message"
end
models>subject.rb
class Subject < ActiveRecord::Base
has_many :books
end
controllers>book_controller.rb
class BookController < ApplicationController
def list
#books = Book.find(:all)
end
def show
#book = Book.find(params[:id])
end
def new
#book = Book.new
#subjects = Subject.find(:all)
end
def create
#book = Book.new(params[:book])
if #book.save
redirect_to :action => 'list'
else
#subjects = Subject.find(:all)
render :action => 'new'
end
end
def edit
#book = Book.find(params[:id])
#subjects = Subject.find(:all)
end
def update
#book = Book.find(params[:id])
if #book.update_attributes(params[:book])
redirect_to :action => 'show', :id => #book
else
#subjects = Subject.find(:all)
render :action => 'edit'
end
end
def delete
Book.find(params[:id]).destroy
redirect_to :action => 'list'
end
def show_subjects
#subject = Subject.find(params[:id])
end
end
There are a couple of issues I'm seeing. For one, your controller should be BooksController and not BookController (you'll also need to ensure it's in a file called books_controller.rb). Two, when you do resources :books, Rails will create the following routes
GET /books -> index
GET /books/:id -> show
GET /books/:id/edit -> edit
PUT /books/:id -> update
GET /books/new -> new
POST /books -> create
DELETE /books/:id -> destroy
As you can see, list is not one of the routes created, which is why you're getting that error message.
Extending #BartJedrocha's answer, first of all with your current routes i.e.
resources: :books
your application should not work and give you a Syntax error syntax error, unexpected ':', expecting keyword_end (SyntaxError).
As resources is a method invocation with argument :books.
So your route should be
resources :books ## Notice no : after "resources"
You have defined resources :books in your routes.So your controller Class name should be Plural ie., BooksController not BookController.So is the error.
Change your controller class name to BooksController and your filename to books_controller.rb
OR
update your routes to
resource :book #not singular
Note: I prefer the first way,because it suites the Rails convention
Update
You have to update your routes to like this
resources :books do
collection do
get 'list'
end
end
This will enable Rails to recognize the path /books/list with GET, and route to the list action of BooksController.

cant pass param through link_to (rails)

I have a problem with passing params. in show view i have
=link_to "Send message", {:controller => "users", :action =>
"send_message", :user_id => #user.id}
and my users_controller have method
def send_message
#user = User.find(params[:user_id])
#message=Message.new
redirect_to send_message_path
end
and my show method
def show
#user = User.find(params[:id])
#post=Post.new
#posts=#user.posts.reverse.paginate(:page => params[:page],:per_page => 10)
end
but i have and error after clicking on link
Couldn't find User without an ID
in that line, in send_message method
#user = User.find(params[:user_id])
what i am doing wrong? i read a lot examples about this , but it doesnt work(
Thanks in advance!!!
=link_to "Send message", [:send_message, #user]
and in your routes:
resources :users do
post :send_message, :on => :collection
end
What happens if you try to change :user_id to :id, like this
=link_to "Send message", {:controller => "users", :action => "send_message", :id => #user.id}
def send_message
#user = User.find(params[:id])
#message=Message.new
redirect_to send_message_path
end
If that works it's because your route isn't set up to use a :user_id param. If it doesn't it would help to know more about your route.
In your routes you should write:
resources :users do
post :send_message, :on => :member
end
And in your view you write:
= link_to "Send Message", send_message_user_path(#user)
This will use id instead of user_id.
So in your controller you need to use params[:id] as well.
Imho this is cleaner than #fl00r solution, because it is a member method, not a collection.
But I am a bit confused as to why you would have that method inside the controller at all.
Because the only thing it does is redirect to the send_message_path anyway. The instance variables you set are all lost then. So instead in your view write this:
= link_to 'Send message', send_message_path(:user_id => #user.id)
And this will send you to the correct controller straightaway (where you will have to retrieve the user).
Also your show method could use some work: you should define a has_many :posts in your User model.

Help: Adding rating to existing posts model in Rails

I've a simple posts model with title:string and rating:integer and I want to add the ability to rate the posts. So far I have
#Post controller
def increase
#post = Post.find(params[:id])
#post.increment! :rating
flash[:notice] = "Thanks for your rating."
redirect_to #post
end
#Post show
<%= link_to "Rating", increase_post_path %>
#Routes
map.resources :posts, :member => { :increase => :put }
When I click on rating, I get unknown action. I'm able to increase the rating when I add #post.increment! :rating to update, but not when I create my own method. Any suggetions?
If you have a standard routes saying
map.resources :posts
you should replace it with:
map.resources :posts, :member => { :increase => :put }
And this will create the route "increase_post_path" with method "put" for your app.
You need to add the action to your routes.rb file. See this excellent guide for details.
Here's my solution, if anyone is interested. Thanks for your help guys.
#Views
<%= link_to post.rating, increase_post_path(post) %>
#Controller
def increase
#post = Post.find(params[:id]).increment!(:rating)
flash[:notice] = "Thanks for rating"
redirect_to posts_url
end
#Routes
map.resources :posts, :member => { :increase => :put }
This works if you want something just for you, something that won't be abused. Obviously adding rating to your websites where others can vote up unlimited times is just asking for trouble.
I suggest using Votefu, does ratings and even has user karma. The author was nice enough to make an example app.

Resources