Rails 4.2: Unable to add search functionality. - ruby-on-rails

Trying to add simple search functionality to my app so anyone can search articles. After adding the code ,it does not display the search results on the index. But the url shows http://localhost:3000/articles?utf8=%E2%9C%93&search=hello&commit=Search
index.html.erb
<p>This is the articles placeholder</p>
<%= form_tag articles_path, :method => 'get' do %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search" %>
<% end %>
<% #articles.each do |article| %>
<h2><%= link_to article.title, article %></h2>
<p>Published at
<%= article.created_at.strftime('%b %d, %Y') %>
</p>
<p>
<%= truncate(article.content, length: 200) %>
</p>
<% end %>
articles controller
class ArticlesController < ApplicationController
before_action :find_article, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
#articles = Article.search(params[:search])
#articles = Article.all.order("created_at DESC")
end
def new
#article = current_user.articles.build
end
def show
end
def create
#article = current_user.articles.build(article_params)
if #article.save
redirect_to #article
else
render 'new'
end
end
def edit
end
def update
if #article.update(article_params)
redirect_to #article
else
render 'edit'
end
end
def destroy
#article.destroy
redirect_to root_path
end
private
def article_params
params.require(:article).permit(:title, :content)
end
def find_article
#article = Article.find(params[:id])
end
end
article.rb
class Article < ActiveRecord::Base
belongs_to :user
def self.search(search)
if search
where(["name LIKE ?", "%#{search}%"])
else
all
end
end
end
rake routes
new_user_session GET /users/sign_in(.:format) devise/sessions#new
user_session POST /users/sign_in(.:format) devise/sessions#create
destroy_user_session DELETE /users/sign_out(.:format) devise/sessions#destroy
user_password POST /users/password(.:format) devise/passwords#create
new_user_password GET /users/password/new(.:format) devise/passwords#new
edit_user_password GET /users/password/edit(.:format) devise/passwords#edit
PATCH /users/password(.:format) devise/passwords#update
PUT /users/password(.:format) devise/passwords#update
cancel_user_registration GET /users/cancel(.:format) devise/registrations#cancel
user_registration POST /users(.:format) devise/registrations#create
new_user_registration GET /users/sign_up(.:format) devise/registrations#new
edit_user_registration GET /users/edit(.:format) devise/registrations#edit
PATCH /users(.:format) devise/registrations#update
PUT /users(.:format) devise/registrations#update
DELETE /users(.:format) devise/registrations#destroy
articles GET /articles(.:format) articles#index
POST /articles(.:format) articles#create
new_article GET /articles/new(.:format) articles#new
edit_article GET /articles/:id/edit(.:format) articles#edit
article GET /articles/:id(.:format) articles#show
PATCH /articles/:id(.:format) articles#update
PUT /articles/:id(.:format) articles#update
DELETE /articles/:id(.:format) articles#destroy
root GET / articles#index

You're overwrite the search by then calling Article.all.order("created_at DESC") and assigning that to the #articles variable
#articles = Article.search(params[:search])
#articles = Article.all.order("created_at DESC")
So you want
#articles = Article.search(params[:search]).order("created_at DESC")
because your search method will return all if the parameters aren't present anyway.

Related

Missing path helper after associating two models

Background
I am following an outdated beginner's Ruby course and got stuck. During this course, I am building a Ruby on rails application similar to Yelp, so it is for listing and reviewing restaurants. Currently, I am linking the reviews to the restaurants.
My ruby version is: ruby 3.0.0p0 (2020-12-25 revision 95aff21468) [x86_64-darwin22]
My rails version is: Rails 7.0.4.2
Steps
I am linking the reviews to the restaurants by executing the following steps:
Run rails generate migration AddRestaurantIDToReviews restaurant_id:integer
Run rake db:migrate
Add belongs_to :restaurant to reviews.rb
Add has_many :reviews to restaurants.rb
Check rails routes
Adjusted routes.rb file
Adjusted reviews_form.html.erb
Adjusted review_controller.rb file
set_restaurant and set_restaurant before action
Add #review statement for restaurant_id (line …)
Removed links that point to old URLs
Restart server
Error message
This resulted in the following error: undefined method `reviews_path' for #ActionView::Base:0x00000000025800 and this is triggered by this line of code: <%= form_with(model: [#resturant, #review], local: true) do |form| %> (from the reviews _form.html.erb file). In this thread a similar issue is explained, but I still can't figure it out.
Could someone help me with this? And if you need more info, please let me know!
Review.rb
class Review < ApplicationRecord
belongs_to :user
belongs_to :restaurant
end
Restaurant.rb
class Restaurant < ApplicationRecord
mount_uploader :image, ImageUploader
has_many :reviews
end
Routes.rb
Rails.application.routes.draw do
devise_for :users
resources :restaurants do
resources :reviews, except: [:show, :index]
end
get 'pages/about'
get 'pages/contact'
root 'restaurants#index'
# Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html
# Defines the root path route ("/")
# root "articles#index"
end
**Routes**
` Prefix Verb URI Pattern Controller#Action
new_user_session GET /users/sign_in(.:format) devise/sessions#new
user_session POST /users/sign_in(.:format) devise/sessions#create
destroy_user_session DELETE /users/sign_out(.:format) devise/sessions#destroy
new_user_password GET /users/password/new(.:format) devise/passwords#new
edit_user_password GET /users/password/edit(.:format) devise/passwords#edit
user_password PATCH /users/password(.:format) devise/passwords#update
PUT /users/password(.:format) devise/passwords#update
POST /users/password(.:format) devise/passwords#create
cancel_user_registration GET /users/cancel(.:format) devise/registrations#cancel
new_user_registration GET /users/sign_up(.:format) devise/registrations#new
edit_user_registration GET /users/edit(.:format) devise/registrations#edit
user_registration PATCH /users(.:format) devise/registrations#update
PUT /users(.:format) devise/registrations#update
DELETE /users(.:format) devise/registrations#destroy
POST /users(.:format) devise/registrations#create
restaurant_reviews POST /restaurants/:restaurant_id/reviews(.:format) reviews#create
new_restaurant_review GET /restaurants/:restaurant_id/reviews/new(.:format) reviews#new
edit_restaurant_review GET /restaurants/:restaurant_id/reviews/:id/edit(.:format) reviews#edit
restaurant_review PATCH /restaurants/:restaurant_id/reviews/:id(.:format) reviews#update
PUT /restaurants/:restaurant_id/reviews/:id(.:format) reviews#update
DELETE /restaurants/:restaurant_id/reviews/:id(.:format) reviews#destroy
restaurants GET /restaurants(.:format) restaurants#index
POST /restaurants(.:format) restaurants#create
new_restaurant GET /restaurants/new(.:format) restaurants#new
edit_restaurant GET /restaurants/:id/edit(.:format) restaurants#edit
restaurant GET /restaurants/:id(.:format) restaurants#show
PATCH /restaurants/:id(.:format) restaurants#update
PUT /restaurants/:id(.:format) restaurants#update
DELETE /restaurants/:id(.:format) restaurants#destroy
pages_about GET /pages/about(.:format) pages#about
pages_contact GET /pages/contact(.:format) pages#contact
root GET / restaurants#index
turbo_recede_historical_location GET /recede_historical_location(.:format) turbo/native/navigation#recede
turbo_resume_historical_location GET /resume_historical_location(.:format) turbo/native/navigation#resume
turbo_refresh_historical_location GET /refresh_historical_location(.:format) turbo/native/navigation#refresh
rails_postmark_inbound_emails POST /rails/action_mailbox/postmark/inbound_emails(.:format) action_mailbox/ingresses/postmark/inbound_emails#create
rails_relay_inbound_emails POST /rails/action_mailbox/relay/inbound_emails(.:format) action_mailbox/ingresses/relay/inbound_emails#create
rails_sendgrid_inbound_emails POST /rails/action_mailbox/sendgrid/inbound_emails(.:format) action_mailbox/ingresses/sendgrid/inbound_emails#create
rails_mandrill_inbound_health_check GET /rails/action_mailbox/mandrill/inbound_emails(.:format) action_mailbox/ingresses/mandrill/inbound_emails#health_check
rails_mandrill_inbound_emails POST /rails/action_mailbox/mandrill/inbound_emails(.:format) action_mailbox/ingresses/mandrill/inbound_emails#create
rails_mailgun_inbound_emails POST /rails/action_mailbox/mailgun/inbound_emails/mime(.:format) action_mailbox/ingresses/mailgun/inbound_emails#create
rails_conductor_inbound_emails GET /rails/conductor/action_mailbox/inbound_emails(.:format) rails/conductor/action_mailbox/inbound_emails#index
POST /rails/conductor/action_mailbox/inbound_emails(.:format) rails/conductor/action_mailbox/inbound_emails#create
new_rails_conductor_inbound_email GET /rails/conductor/action_mailbox/inbound_emails/new(.:format) rails/conductor/action_mailbox/inbound_emails#new
edit_rails_conductor_inbound_email GET /rails/conductor/action_mailbox/inbound_emails/:id/edit(.:format) rails/conductor/action_mailbox/inbound_emails#edit
rails_conductor_inbound_email GET /rails/conductor/action_mailbox/inbound_emails/:id(.:format) rails/conductor/action_mailbox/inbound_emails#show
PATCH /rails/conductor/action_mailbox/inbound_emails/:id(.:format) rails/conductor/action_mailbox/inbound_emails#update
PUT /rails/conductor/action_mailbox/inbound_emails/:id(.:format) rails/conductor/action_mailbox/inbound_emails#update
DELETE /rails/conductor/action_mailbox/inbound_emails/:id(.:format) rails/conductor/action_mailbox/inbound_emails#destroy
new_rails_conductor_inbound_email_source GET /rails/conductor/action_mailbox/inbound_emails/sources/new(.:format) rails/conductor/action_mailbox/inbound_emails/sources#new
rails_conductor_inbound_email_sources POST /rails/conductor/action_mailbox/inbound_emails/sources(.:format) rails/conductor/action_mailbox/inbound_emails/sources#create
rails_conductor_inbound_email_reroute POST /rails/conductor/action_mailbox/:inbound_email_id/reroute(.:format) rails/conductor/action_mailbox/reroutes#create
rails_conductor_inbound_email_incinerate POST /rails/conductor/action_mailbox/:inbound_email_id/incinerate(.:format) rails/conductor/action_mailbox/incinerates#create
rails_service_blob GET /rails/active_storage/blobs/redirect/:signed_id/*filename(.:format) active_storage/blobs/redirect#show
rails_service_blob_proxy GET /rails/active_storage/blobs/proxy/:signed_id/*filename(.:format) active_storage/blobs/proxy#show
GET /rails/active_storage/blobs/:signed_id/*filename(.:format) active_storage/blobs/redirect#show
rails_blob_representation GET /rails/active_storage/representations/redirect/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations/redirect#show
rails_blob_representation_proxy GET /rails/active_storage/representations/proxy/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations/proxy#show
GET /rails/active_storage/representations/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations/redirect#show
rails_disk_service GET /rails/active_storage/disk/:encoded_key/*filename(.:format) active_storage/disk#show
update_rails_disk_service PUT /rails/active_storage/disk/:encoded_token(.:format) active_storage/disk#update
rails_direct_uploads POST /rails/active_storage/direct_uploads(.:format) active_storage/direct_uploads#create`
Review _form.html.erb
<%= form_with(model: [#resturant, #review], local: true) do |form| %>
<% if review.errors.any? %>
<div style="color: red">
<h2><%= pluralize(review.errors.count, "error") %> prohibited this review from being saved:</h2>
<ul>
<% review.errors.each do |error| %>
<li><%= error.full_message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-group">
<%= form.label :rating, style: "display: block" %>
<%= form.number_field :rating, class: "form-control" %>
</div>
<div class="form-group">
<%= form.label :comment, style: "display: block" %>
<%= form.text_area :comment, class: "form-control" %>
</div>
<div>
<%= form.submit class: "btn btn-primary" %>
</div>
<% end %>
Reviews_controller.rb
class ReviewsController < ApplicationController
before_action :set_review, only: %i[ edit update destroy ]
before_action :set_restaurant
before_action :authenticate_user!
# GET /reviews/new
def new
#review = Review.new
end
# GET /reviews/1/edit
def edit
end
# POST /reviews or /reviews.json
def create
#review = Review.new(review_params)
#review.user_id = current_user.id
#review.restaurant_id = #restaurant.id
respond_to do |format|
if #review.save
format.html { redirect_to root_path, notice: "Review was successfully created." }
format.json { render :show, status: :created, location: #review }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #review.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /reviews/1 or /reviews/1.json
def update
respond_to do |format|
if #review.update(review_params)
format.html { redirect_to review_url(#review), notice: "Review was successfully updated." }
format.json { render :show, status: :ok, location: #review }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: #review.errors, status: :unprocessable_entity }
end
end
end
# DELETE /reviews/1 or /reviews/1.json
def destroy
#review.destroy
respond_to do |format|
format.html { redirect_to reviews_url, notice: "Review was successfully destroyed." }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_review
#review = Review.find(params[:id])
end
def set_restaurant
#restaurant = Restaurant.find(params[:restaurant_id])
end
# Only allow a list of trusted parameters through.
def review_params
params.require(:review).permit(:rating, :comment)
end
end
The url: restaurant_reviews_path addition to the form_with made the difference.
<%= form_with(model: #review, url: restaurant_reviews_path, local: true) do |form| %>

Couldn't find Post with 'id'=testuser

When I go to delete a post I get the error "Couldn't find Post with 'id'=testuser". I think this is a routing error as I believe the id being ran should be that of the Post and not the User? I can't work it out. I can create posts but can't delete or edit for the same reasons.
I can provide more information if needed.
The extracted source in PostController#destroy is where:
def set_post
#work = Work.find(params[:id])
routes.rb
Rails.application.routes.draw do
devise_for :users, :controllers => { :registrations => "registrations" }
resources :posts do
end
# Define route URL
root 'pages#index'
# Define routes for Pages
get '/home' => 'pages#home'
get '/user/:id' => 'pages#profile'
get '/new' => 'posts#new'
Pages_controller.rb
class PagesController < ApplicationController
def index
end
def home
end
def profile
if (User.find_by_username(params[:id]))
#username = params[:id]
else
redirect_to root_path, :notice=> "User not found!"
end
#posts = Post.all.where("user_id = ?", User.find_by_username(params[:id]).id)
#newPost = Post.new
end
end
Posts_controller.rb
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
def create
#post = Post.new(post_params)
#post.user_id = current_user.id #assign post to the user who created it
respond_to do |f|
if (#post.save)
f.html { redirect_to "", notice: "Post created!" }
else
f.html { redirect_to "", notice: "Error: Post Not Saved" }
end
end
end
def show
end
def edit
respond_to do |format|
if #post.update(post_params)
format.html { redirect_to #post, notice: 'Your post was successfully updated.' }
format.json { render :show, status: :ok, location: #post }
else
format.html { render :edit }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
def destroy
#post.destroy
respond_to do |format|
format.html { redirect_to root_path, notice: 'Post was successfully deleted.' }
format.json { head :no_content }
end
end
private
def set_post
#post = Post.find(params[:id])
end
def post_params #allows certain data to be passed via form
params.require(:post).permit(:user_id, :title, :description, :image)
end
end
Profile.html.erb
...
<%= link_to('Delete', post_path, :method => :delete) %>
...
Terminal
Prefix Verb URI Pattern Controller#Action
new_user_session GET /users/sign_in(.:format) devise/sessions#new
user_session POST /users/sign_in(.:format) devise/sessions#create
destroy_user_session DELETE /users/sign_out(.:format) devise/sessions#destroy
user_password POST /users/password(.:format) devise/passwords#create
new_user_password GET /users/password/new(.:format) devise/passwords#new
edit_user_password GET /users/password/edit(.:format) devise/passwords#edit
PATCH /users/password(.:format) devise/passwords#update
PUT /users/password(.:format) devise/passwords#update
cancel_user_registration GET /users/cancel(.:format) registrations#cancel
user_registration POST /users(.:format) registrations#create
new_user_registration GET /users/sign_up(.:format) registrations#new
edit_user_registration GET /users/edit(.:format) registrations#edit
PATCH /users(.:format) registrations#update
PUT /users(.:format) registrations#update
DELETE /users(.:format) registrations#destroy
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PATCH /posts/:id(.:format) posts#update
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
root GET / pages#index
home GET /home(.:format) pages#home
GET /user/:id(.:format) pages#profile
connect GET /connect(.:format) pages#connect
help GET /help(.:format) pages#help
messages GET /messages(.:format) pages#messages
new GET /new(.:format) posts#new
You did not pass id or instance in link of delete
<%= link_to('Delete', post_path, :method => :delete) %>
Should be pass a post instance on the delete link so that in find it find the post
<%= link_to('Delete', post_path(post), :method => :delete) %>
or
<%= link_to('Delete', post_path(post.id), :method => :delete) %>

editing namespaced resource

I'm trying to hook up a link that will take users from a lesson show page (that lists a bunch of words) to a form to edit one of the listed words. I have a teacher namespace, such that teachers have many lessons and lessons have many words. Before working on a form to edit the word, the lesson show page is breaking when I add the link to what would be the edit form: ActionController::UrlGenerationError in Teacher::Lessons#show, No route matches {:action=>"edit", :controller=>"teacher/words", :id=>nil, :lesson_id=>#<Word id: 19, term: "la casa", reference: "house", lesson_id: 6, created_at: "2016-06-05 23:19:19", updated_at: "2016-06-05 23:19:19", image: "house.jpeg", sound: "test.mp3">} missing required keys: [:id]
What am I missing in regards to setting the edit_teacher_lesson_word link?
Rails.application.routes.draw do
devise_for :users
root 'static_pages#index'
resources :lessons, only: [:index, :show]
resources :words, only: [:show]
namespace :teacher do
resources :lessons, only: [:show, :new, :edit, :create, :update] do
resources :words, only: [:new, :edit, :create, :update]
end
end
end
teacher/words_controller:
class Teacher::WordsController < ApplicationController
before_action :authenticate_user!
before_action :require_authorized_for_current_lesson
def new
#word = Word.new
end
def edit
#word = Word.find(params[:id])
end
def create
#word = current_lesson.words.create(word_params)
if #word.valid?
redirect_to teacher_lesson_path(current_lesson)
else
render :new, status: :unprocessable_entity
end
end
private
def require_authorized_for_current_lesson
if current_lesson.user != current_user
render text: 'Unauthorized', status: :unauthorized
end
end
helper_method :current_lesson
def current_lesson
#current_lesson ||= Lesson.find(params[:lesson_id])
end
def word_params
params.require(:word).permit(:term, :reference, :image, :sound)
end
end
teacher/lessons_controller:
class Teacher::LessonsController < ApplicationController
before_action :authenticate_user!
before_action :require_authorized_for_current_lesson, only: [:show, :edit, :update]
def show
#lesson = Lesson.find(params[:id])
end
def new
#lesson = Lesson.new
end
def edit
#lesson = Lesson.find(params[:id])
end
def create
#lesson = current_user.lessons.create(lesson_params)
if #lesson.valid?
redirect_to teacher_lesson_path(#lesson)
else
render :new, status: :unprocessable_entity
end
end
def update
current_lesson.update_attributes(lesson_params)
redirect_to teacher_lesson_path(current_lesson)
end
private
def require_authorized_for_current_lesson
if current_lesson.user != current_user
render text: "Unauthorized", status: :unauthorized
end
end
def current_lesson
#current_lesson ||= Lesson.find(params[:id])
end
def lesson_params
params.require(:lesson).permit(:title, :description, :subject, :difficulty)
end
end
teacher/lessons/show:
<div class ="booyah-box col-xs-10 col-xs-offset-1">
<br>
<p class="text-center"><%= #lesson.description %></p>
<br>
<div class="text-center">
<%= link_to 'Edit Lesson', edit_teacher_lesson_path(#lesson), class: 'btn btn-primary' %>
<%= link_to 'Student View', lesson_path(#lesson), class: 'btn btn-warning' %>
<%= link_to 'My Lessons', '#', class: 'btn btn-success' %>
<%= link_to 'All Lessons', lessons_path, class: 'btn btn-info' %>
</div>
<hr>
<h3>Vocabulary in This Lesson</h3>
<%= link_to 'Add word', new_teacher_lesson_word_path(#lesson), class: 'btn btn-primary btn-lg pull-right' %>
<ul>
<% #lesson.words.each do |word| %>
<li>
<b><%= word.term %></b> means <i><%= word.reference %></i>
<%= link_to 'Edit', edit_teacher_lesson_word_path(word), class: 'btn btn-primary' %>
</li>
<% end %>
</ul>
</div>
rake routes:
new_user_session GET /users/sign_in(.:format) devise/sessions#new
user_session POST /users/sign_in(.:format) devise/sessions#create
destroy_user_session DELETE /users/sign_out(.:format) devise/sessions#destroy
user_password POST /users/password(.:format) devise/passwords#create
new_user_password GET /users/password/new(.:format) devise/passwords#new
edit_user_password GET /users/password/edit(.:format) devise/passwords#edit
PATCH /users/password(.:format) devise/passwords#update
PUT /users/password(.:format) devise/passwords#update
cancel_user_registration GET /users/cancel(.:format) devise/registrations#cancel
user_registration POST /users(.:format) devise/registrations#create
new_user_registration GET /users/sign_up(.:format) devise/registrations#new
edit_user_registration GET /users/edit(.:format) devise/registrations#edit
PATCH /users(.:format) devise/registrations#update
PUT /users(.:format) devise/registrations#update
DELETE /users(.:format) devise/registrations#destroy
root GET / static_pages#index
lessons GET /lessons(.:format) lessons#index
lesson GET /lessons/:id(.:format) lessons#show
word GET /words/:id(.:format) words#show
teacher_lesson_words POST /teacher/lessons/:lesson_id/words(.:format) teacher/words#create
new_teacher_lesson_word GET /teacher/lessons/:lesson_id/words/new(.:format) teacher/words#new
edit_teacher_lesson_word GET /teacher/lessons/:lesson_id/words/:id/edit(.:format) teacher/words#edit
teacher_lesson_word PATCH /teacher/lessons/:lesson_id/words/:id(.:format) teacher/words#update
PUT /teacher/lessons/:lesson_id/words/:id(.:format) teacher/words#update
teacher_lessons POST /teacher/lessons(.:format) teacher/lessons#create
new_teacher_lesson GET /teacher/lessons/new(.:format) teacher/lessons#new
edit_teacher_lesson GET /teacher/lessons/:id/edit(.:format) teacher/lessons#edit
teacher_lesson GET /teacher/lessons/:id(.:format) teacher/lessons#show
PATCH /teacher/lessons/:id(.:format) teacher/lessons#update
PUT /teacher/lessons/:id(.:format) teacher/lessons#update
looks like you're passing a Word where it's expecting a Lesson. see this part of the error message: :lesson_id=>#<Word id: 19,
I'm guessing, but probably this is the wrong line of code:
edit_teacher_lesson_word_path(word)
your route file says this about that route:
edit_teacher_lesson_word GET /teacher/lessons/:lesson_id/words/:id/edit(.:format)
the : indicates what things you need to pass in order to create a valid route... and here you need both :lesson_id as well as :id and you are only passing one of those (and it's getting confused about which one).
Usually you'd instantiate this route with both lesson and word eg:
edit_teacher_lesson_word_path(#lesson, word)
Try that (or variations on it) to get it to work.

No route matches {:action=>"show"

I have a view which lists all my comparisons
index.html.erb
<% #comparisons.each do |comparison| %>
<div class="col-xs-6 col-sm-4 col-md3">
<p><%= comparison.title %></p>
<p><%= comparison.id %></p>
<p><%= comparison.description %></p>
</div>
<% end %>
Up to now, all is going well : title, description and id are displayed for each comparison.
I tried to add a Show link :
<% #comparisons.each do |comparison| %>
<div class="col-xs-6 col-sm-4 col-md3">
<p><%= comparison.title %></p>
<p><%= comparison.id %></p>
<p><%= comparison.description %></p>
<p><%= link_to 'Show', comparison_path(comparison) %></p>
</div>
<% end %>
But now, when I load index.html.erb I have this error :
No route matches {:action=>"show", :controller=>"comparisons", :format=>nil, :id=>nil, :locale=>#<Comparison id: 1, title: "coucou", description: "", created_at: "2015-07-04 10:33:47", updated_at: "2015-07-04 10:33:47", user_id: 1>} missing required keys: [:id]
I don't understand why...
comparisons_controller.rb
class ComparisonsController < ApplicationController
before_action :set_comparison, only: [ :show ]
skip_before_action :authenticate_user!, only: [ :index, :show ]
def index
#comparisons = policy_scope(Comparison)
end
def show
end
def new
#comparison = current_user.comparisons.new
authorize #comparison
end
def create
#comparison = current_user.comparisons.new(comparison_params)
authorize #comparison
if #comparison.save
# redirect_to comparison_path(#comparison)
# redirect_to #comparison
render :show
else
render :new
end
end
private
def set_comparison
#comparison = Comparison.find(params[:id])
authorize #comparison
end
def comparison_params
params.require(:comparison).permit(:title, :description, :user_id)
end
end
By the way, as you can see, in create action, I have not been able to use a redirect_to. But render :show works : the show.html.erb view is loaded.
Any risks to use render rather redirect_to ?
My routes
Prefix Verb URI Pattern Controller#Action
new_user_session GET /users/sign_in(.:format) devise/sessions#new
user_session POST /users/sign_in(.:format) devise/sessions#create
destroy_user_session DELETE /users/sign_out(.:format) devise/sessions#destroy
user_password POST /users/password(.:format) devise/passwords#create
new_user_password GET /users/password/new(.:format) devise/passwords#new
edit_user_password GET /users/password/edit(.:format) devise/passwords#edit
PATCH /users/password(.:format) devise/passwords#update
PUT /users/password(.:format) devise/passwords#update
cancel_user_registration GET /users/cancel(.:format) devise/registrations#cancel
user_registration POST /users(.:format) devise/registrations#create
new_user_registration GET /users/sign_up(.:format) devise/registrations#new
edit_user_registration GET /users/edit(.:format) devise/registrations#edit
PATCH /users(.:format) devise/registrations#update
PUT /users(.:format) devise/registrations#update
DELETE /users(.:format) devise/registrations#destroy
page GET (/:locale)/pages/:id high_voltage/pages#show {:locale=>/fr/}
comparisons GET (/:locale)/comparisons(.:format) comparisons#index {:locale=>/fr/}
POST (/:locale)/comparisons(.:format) comparisons#create {:locale=>/fr/}
new_comparison GET (/:locale)/comparisons/new(.:format) comparisons#new {:locale=>/fr/}
comparison GET (/:locale)/comparisons/:id(.:format) comparisons#show {:locale=>/fr/}
home GET /home(.:format) redirect(301, /)
root GET / high_voltage/pages#show {:id=>"home"}
routes.rb
Rails.application.routes.draw do
devise_for :users
scope '(:locale)', locale: /fr/ do
get 'pages/:id' => 'high_voltage/pages#show', :as => :page, :format => false
resources :comparisons, only: [ :index, :show, :new, :create ]
end
end
Thanks in advance for your help.
Seeing from your routes files, it looks to me that to construct a route, you need two parameters - locale and id. Since you are using comparison_path(comparison), rails is assuming that the first parameter you are passing refers to locale.
To construct a correct route, use a cleaner way to construct a route - like this:
comparison_path(locale: 'en', id: comparison.id)
Previous answers made me realize I had a routing issue with i18n : locale parameter was not considered in urls building.
In application_controller.rb I still have
before_action :set_locale
private
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
I add this second method which automatically add the locale parameter to urls
def default_url_options
{ locale: I18n.locale == I18n.default_locale ? nil : I18n.locale }
end
Now, it works fine.
Thanks for your help.
Alternatively you can use like this:
<% #comparisons.each do |comparison| %>
<div class="col-xs-6 col-sm-4 col-md3">
<p><%= comparison.title %></p>
<p><%= comparison.id %></p>
<p><%= comparison.description %></p>
<p><%= link_to 'Show', comparison %></p>
</div>
<% end %>
It seems to me using :shallow_path would be the answer. From the documentation.
The :path, :as, :module, :shallow_path and :shallow_prefix options all default to the name of the namespace.
I think this will remove (/:locale) from the raked routes
scope '(:locale)', locale: /fr/, :shallow_path => '(:locale)' do
get 'pages/:id' => 'high_voltage/pages#show', :as => :page, :format => false
resources :comparisons, only: [ :index, :show, :new, :create ]
end

Routing Error uninitialized constant Comments – Making Nested comments

I'm learning Rails. I've got an app that has "Ideas", which have "Comments"
I've created the comments using this guide (https://gorails.com/episodes/comments-with-polymorphic-associations)
I am using the 'Ancestry' gem to attempt make them nested using this guide on railscasts (http://railscasts.com/episodes/262-trees-with-ancestry)
Anyways I'm getting this error "ActionController::RoutingError (uninitialized constant Comments):"
This is where I'm getting the error – when I hit the "Reply" link
<h3> Comments </h3>
<% #idea.comments.each do |comment| %>
<div>
<%= comment.body %>
<div class="actions">
<%= link_to "Reply", new_comment_path(:parent_id => comment) %>
</div>
</div>
<% end %>
The above is being rendered on the "Ideas/show.html" page
<p id="notice"><%= notice %></p>
<p>
<strong>Description:</strong>
<%= #idea.description %>
</p>
<%= render partial: "comments/comments", locals: {commentable: #idea} %>
<%= render partial: "comments/form", locals: {commentable: #idea} %>
<% if #idea.user == current_user %>
<%= link_to 'Edit', edit_idea_path(#idea) %>
<% end %>
<%= link_to 'Back', ideas_path %>
I want to send them here to "Comments/new" which is the same as my form page
<%= form_for [commentable, Comment.new] do |f| %>
<div class="form-group">
<%= f.hidden_field :parent_id %>
<%= f.text_area :body, class: "form-control", placeholder: "Add a comment here" %>
</div>
<%= f.submit class: "btn btn-primary" %>
<% end %>
Routes.rb
Rails.application.routes.draw do
resources :ideas do
resources :comments, module: :ideas
end
devise_for :users
root 'ideas#index'
get "about" => "pages#about"
get "new_comment" => "comments/new"
end
Comments_controller.rb
class CommentsController < ApplicationController
before_action :authenticate_user!
def new
#comment = Comment.new(:parent_id => params[:parent_id])
end
def create
#comment = #commentable.comments.new comment_params
#comment.user = current_user
#comment.save
redirect_to #commentable, notice: "Your comment was posted"
end
private
def comment_params
params.require(:comment).permit(:body)
end
end
Ideas_controller.rb
class IdeasController < ApplicationController
before_action :set_idea, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
before_action :correct_user, only: [:edit, :update, :destroy]
respond_to :html
def index
#ideas = Idea.all
end
def show
end
def new
#idea = Idea.new
#idea.comments.build
respond_with(#idea)
end
def edit
end
def create
#idea = current_user.ideas.build(idea_params)
if #idea.save
redirect_to #idea, notice: "Idea was successfully created."
else
render :action => 'new'
end
end
def update
if #idea.update(idea_params)
redirect_to #idea, notice: "Your idea has been updated"
else
render action: 'edit'
end
end
def destroy
#idea.destroy
redirect_to ideas_url
end
private
def set_idea
#idea = Idea.find(params[:id])
end
def correct_user
#idea = current_user.ideas.find_by(id: params[:id])
redirect_to ideas_path, notice: "You can't edit this" if #idea.nil?
end
def idea_params
params.require(:idea).permit(:description)
end
end
Any help would be much appreciated, thank you.
EDIT _ Added my routes
idea_comments GET /ideas/:idea_id/comments(.:format) ideas/comments#index
POST /ideas/:idea_id/comments(.:format) ideas/comments#create
new_idea_comment GET /ideas/:idea_id/comments/new(.:format) ideas/comments#new
edit_idea_comment GET /ideas/:idea_id/comments/:id/edit(.:format) ideas/comments#edit
idea_comment GET /ideas/:idea_id/comments/:id(.:format) ideas/comments#show
PATCH /ideas/:idea_id/comments/:id(.:format) ideas/comments#update
PUT /ideas/:idea_id/comments/:id(.:format) ideas/comments#update
DELETE /ideas/:idea_id/comments/:id(.:format) ideas/comments#destroy
ideas GET /ideas(.:format) ideas#index
POST /ideas(.:format) ideas#create
new_idea GET /ideas/new(.:format) ideas#new
edit_idea GET /ideas/:id/edit(.:format) ideas#edit
idea GET /ideas/:id(.:format) ideas#show
PATCH /ideas/:id(.:format) ideas#update
PUT /ideas/:id(.:format) ideas#update
DELETE /ideas/:id(.:format) ideas#destroy
new_user_session GET /users/sign_in(.:format) devise/sessions#new
user_session POST /users/sign_in(.:format) devise/sessions#create
destroy_user_session DELETE /users/sign_out(.:format) devise/sessions#destroy
user_password POST /users/password(.:format) devise/passwords#create
new_user_password GET /users/password/new(.:format) devise/passwords#new
edit_user_password GET /users/password/edit(.:format) devise/passwords#edit
PATCH /users/password(.:format) devise/passwords#update
PUT /users/password(.:format) devise/passwords#update
cancel_user_registration GET /users/cancel(.:format) devise/registrations#cancel
user_registration POST /users(.:format) devise/registrations#create
new_user_registration GET /users/sign_up(.:format) devise/registrations#new
edit_user_registration GET /users/edit(.:format) devise/registrations#edit
PATCH /users(.:format) devise/registrations#update
PUT /users(.:format) devise/registrations#update
DELETE /users(.:format) devise/registrations#destroy
root GET / ideas#index
about GET /about(.:format) pages#about
new_comment GET /new_comment(.:format) comments/new#new_comment

Resources