passing variables in redirect_to - ruby-on-rails

In my Rails application, in routes.rb I have
match "show_fail" => "Posts#show_fail"
In posts_controller.rb:
def create
...
return redirect_to show_fail_path, :title => #post.title
end
def show_fail
end
In show_fail.html.erb:
Unsuccessful posting of post title <%= title %>
But I got an error undefined local variable or method 'title'. Why does it not know about the title variable, and how can I fix it?

redirect_to show_fail_path(:title => #post.title)
and take it from params[:title]

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} %>

How do I pass the select_tag's input to the rails controller

I'm trying to insert the input from a select_tag to my controller method.
I've looked and cannot seem to resolve the issue.
This is the code I have below, nothing for the rank's selection comes up in the params at all.
<h1>hello please set <%= #user.username %>'s rank'</h1>
<%= select_tag 'rank', options_for_select(#ranks.collect{ |r| [r.rank_name] }) %>
<%= button_to "Update", :action => "set_user_rank_update", value: "#{#user.id}", method: :post %>
Update below with the controller and routes
Controller:
class Admin::RankController < ApplicationController
before_action :admin?
def new
#rank = Rank.new
end
def create
#rank = Rank.new(rank_params)
if params["rank"]["admin"].to_i == 1
#rank.toggle! :admin?
end
if #rank.save
flash[:success] = "Rank created"
redirect_to root_path
else
flash[:danger] = "Failed to create rank"
render 'new'
end
end
def set_user_rank_new
#user = User.find_by_id(params["format"])
#ranks = Rank.all
end
def set_user_rank_update
#user = User.find_by_id(params["value"])
#rank = Rank.find_by_id(params["rank"])
#rank_backup = #user.rank.first
debugger
#user.rank - #user.rank.first
#user.rank << #rank
if #user.rank.first == #rank
flash[:success] = "Set user's rank"
redirect_to root_path
else
flash[:danger] = "Failed to set user's rank"
#user.rank - #user.rank.first
#user.rank << #rank_backup
render 'set_user_rank_new'
end
end
private
def rank_params
params.require(:rank).permit(:rank_name, :rank_color)
end
end
Routes
Rails.application.routes.draw do
devise_for :users,
:controllers => { :registrations => "member/registrations" , :sessions => "member/sessions"}
scope module: 'public' do
root 'welcome#index'
end
scope module: 'member' do
get 'members/:id' => 'member#show'
end
scope module: 'admin' do
get 'rank/new' => 'rank#new'
post 'rank/create' => 'rank#create'
get 'rank/set_user_rank/new' => 'rank#set_user_rank_new'
post 'rank/set_user_rank/update' => 'rank#set_user_rank_update'
end
end
Try passing 2 element arrays to options_for_select. The way you have it looks like it would get you option text but no values, which could explain why it doesn't show up in the params.
So for example:
<%= select_tag 'rank', options_for_select(#ranks.collect{ |r|[r.rank_name, r.id] }) %>
The button_to helper creates an inline form with just the parameters included in the helper statement (in this case the user id).
You can check this by examining the resulting HTML on your page - which I think will show an input field for rank sitting outside the form tag.
To include the rank parameter, you should set up the form using a form helper and make sure the rank input is included inside the form.
For what purpose do you need it in your controller action?
With the link_to you can forwards params as well.
It would be very helpful to see your controller and also your routes.

Rails link_to static pages issue

I don't know an awful lot about Rails and I've inherited this project. For the past few days I've been trying to get my head around, 'link_to', and 'routes.rb'. This stuff is driving me mad - I've spent the whole day looking at it, pasting bits of code into bare projects, where it works..but I just don't understand the error I'm getting here, or how to go about solving it, so if you have any ideas....
In my page _signed_in_header.html.erb I have:
FAQ
In my routes.rb I have:
get "staticpages/faq"
I know this is set up correct, because when I start a sample project from scratch, it works.
But in this particular project I've inherited I get the error:
NoMethodError in Staticpages#faq
Showing /home/christophecompaq/Populisto/app/views/layouts/_signed_in_header.html.erb where line #48 raised:
undefined method `model_name' for NilClass:Class
Extracted source (around line #48):
45:
46: <div class='search-box'>
47: <%= simple_form_for #review, :url => search_index_path, :method => :post, :html => { :class => 'form-horizontal'} do |f| %>
48:
49: <%= f.input :search_ids, :collection => #data, :as => :grouped_chosen,
50: :group_method => :last, :prompt => false,
51: :input_html => { :class => 'span5', :multiple => true },
Trace of template inclusion: app/views/layouts/_header.html.erb, app/views/layouts/application.html.erb
Rails.root: /home/christophecompaq/Populisto
Application Trace | Framework Trace | Full Trace
app/views/layouts/_signed_in_header.html.erb:48:in `_app_views_layouts__signed_in_header_html_erb___586079249_69970641688720'
app/views/layouts/_header.html.erb:1:in `_app_views_layouts__header_html_erb__1905506502_69970640142220'
app/views/layouts/application.html.erb:21:in `_app_views_layouts_application_html_erb___1868096314_69970642536740'
Edit: I was asked to show my review controller code, so here it goes:
class ReviewsController < FrontEndController
respond_to :html, :json
before_filter :with_google_maps_api
def index
#review = Review.new
end
def create
#review = Review.create((params[:review] || {}).merge(:user_id => current_user.id))
if #review.save
redirect_to landing_page, :notice => I18n.t('write_review.review_successfully_created')
else
render :action => :index
end
end
def show
#review = Review.find(params[:id])
end
def edit
#review = Review.find(params[:id])
end
def update
#review = Review.find(params[:id])
if #review.update_attributes(params[:review])
else
render :edit
end
end
def destroy
#review = Review.find(params[:id])
#review.destroy
end
def repost
#review = Review.find(params[:id])
#review.repost(current_user)
end
def reject
#review = Review.find(params[:id])
current_user.reject #review
end
end
Anyway, if you have any ideas what could be wrong, I'd be delighted to know....Thanks.
Christophe.
in your route file, use this code
get "staticpages/faq", :as => 'faq_page'
The 'as' will generate 2 helper functions: faq_page_url and faq_page_path that you can use in your code
i hope this will help, i think we have the same issue but i've managed to fix this using this:
in my routes.rb
match 'pages/:action', :controller => "pages"
and in my view:
= link_to "About", {:controller => 'pages', :action => 'about'}
The error is happening during rendering of the layout template, not the controller view.
If you're testing the faq page you'll be hitting the StaticpagesController, not the ReviewController you pasted right? And presumably StaticpagesController does not set #review... hence your exception.
So either try wrapping the search box code in a conditional like:
<% if #review %>
... put your review search form here ...
<% end %>
or if the search is supposed to present on all pages, ensure it's populated on all pages. Maybe add a before_filter on your base controller class with something like
class ApplicationController < ....
before filter :ensure_review_set
private
def ensure_review_set
#review ||= Review.new
end
end
The search form is also referencing #data if the search_ids field. That will also need to be initialised by any controllers using this layout.
More generally, if your version of rails supports it, I'd very very highly recommend the better_errors gem for quickly debugging errors such as this.

Routes generated paths have stopped working

I'm creating a blog using Rails 3.2.5 and have been using link_to's to each action using the resource paths generated by Routes (i.e. for my code_entries: code_entries_path, new_code_entry_path, etc.) throughout the site. All of a sudden whenever I try to access a page I get this error:
undefined local variable or method `controller' for #<CodeEntriesController:0x007f887f8b3300>
This error is from my index action on my code_entries_controller.rb, but no matter which action I try to go to in any controller I get this error on every link_to with a Routes resource path. It was working fine before and I'm not sure what would have caused this.
Since this question is in the context of my code_entries, here is the code for code_entries_controller.rb, /code_entries/index.html.haml, routes.rb and the error I've been getting but in the context of the action code_entries#index:
code_entries_controller.rb
class CodeEntriesController < ApplicationController
before_filter :authenticate_action
def index
#entries = CodeEntry.order("created_at desc")
end
def new
#entry = CodeEntry.new
end
def show
#entry = CodeEntry.find_by_id(params[:id])
end
def create
#entry = CodeEntry.new(params[:code_entry])
if #entry.save
redirect_to code_entry_path(#entry), :notice => "#{#entry.title} has been created"
else
puts #entry.errors.messages.inspect
render "new"
end
end
def edit
#entry = CodeEntry.find_by_id(params[:id])
end
def update
#entry = CodeEntry.find_by_id(params[:id])
if #entry.update_attributes(params[:code_entry])
redirect_to code_entry_path(#entry), :notice => "#{#entry.title} has been updated"
else
puts #entry.errors.messages.inspect
render "edit"
end
end
def destroy
#entry = CodeEntry.find_by_id(params[:id])
#entry.destroy
redirect_to code_entries_path, :notice => "#{#entry.title} has been deleted"
end
end
/code_entries/index.html.haml
%h1 Hello!
%br
- #entries.each do |e|
%h2= link_to e.title, code_entry_path(e)
%h3= e.updated_at
= raw excerpt(e, 200)
%br
- if current_user
= link_to "Edit", edit_code_entry_path(e)
= button_to "Delete", code_entry_path(e), :confirm => "Really really?", :method => :delete
%hr
routes.rb
Blog::Application.routes.draw do
resources :users
resources :code_entries
resources :food_entries
resources :inclusive_entries
resources :sessions
root :to => "home#index"
get "login" => "sessions#new", :as => "login"
get "logout" => "sessions#destroy", :as => "logout"
get "users/new"
end
NameError in Code_entries#index
Showing /Users/kyle/Projects/blog/app/views/code_entries/index.html.haml where line #4 raised:
undefined local variable or method `controller' for #<CodeEntriesController:0x007f887f813418>
Extracted source (around line #4):
1: %h1 Hello!
2: %br
3: - #entries.each do |e|
4: %h2= link_to e.title, code_entry_path(e)
5: %h3= e.updated_at
6: = raw excerpt(e, 200)
7: %br
Rails.root: /Users/kyle/Projects/blog
Application Trace | Framework Trace | Full Trace
app/views/code_entries/index.html.haml:4:in `block in _app_views_code_entries_index_html_haml___3334012984247114074_70112115764360'
app/views/code_entries/index.html.haml:3:in `_app_views_code_entries_index_html_haml___3334012984247114074_70112115764360'
Request
Parameters:
None
Show session dump
Show env dump
Response
Headers:
None
I had made a method inside of application_controller.rb and used it as an argument with helper_method. Since it was inside of application_controller.rb and not application_helper.rb I had used the tag include ActionView::Helpers::UrlHelper so I could use a link_to inside the helper method. Somehow that include statement was making it blow up, but once I removed the include statement and moved the helper method into application_helper.rb everything turned out fine!

Pass Error Messages When Using form_tag?

How can you pass an error messages coming from a model --> controller to view?
= form_tag :controller => "article", :action => "create" do
/ how to retrieve error messages here?
%p
= label_tag :article, "Article"
= text_field_tag :article
= submit_tag "Submit Article"
I have this model:
class Article < ActiveRecord::Base
attr_accessible :article
validates :article, :presence => true
end
In my controller:
def create
#article = Article.new(params[:article])
if ! #article.save
# how to set errors messages?
end
end
I'm using Rails 3.0.9
The errors messages are stored in your model. You can access through the errors methods, like you can see in http://api.rubyonrails.org/classes/ActiveModel/Errors.html.
An easy way to expose the error message is including the follow line in your view:
%span= #article.errors[:article].first
But, I belive you have to change your controller to be like that:
def new
#article = Artile.new
end
def create
#article = Artile.new params[:article]
if !#article.save
render :action => :new
end
end
In the new action you don't need to try save the article, because the creation action already do that job. The new action exists, (basically) to call the new view and to provide support for validations messages.
The newmethod shouldn't save anything. create method should.
def create
#article = Article.new(params[:article])
if ! #article.save
redirect_to root_path, :error => "ops! something went wrong.."
end
end

Resources