Links with Ruby on Rails - ruby-on-rails

If I have the following code in my controller:
# encoding: utf-8
module Admin
class SylabusController < BaseController
def show_all
#questions = #topic.questions.all
end
And I have the index where I would like to "call" the show_all in order that appears a new web page with all the questions. How does be the link?
<%= link_to 'All the questions'.html_safe, #sylabus.show_all, class: 'btn' %>
With the following error.
NoMethodError in Admin/mupets#index
Showing app/views/admin/sylabus/index.html.erb where line #41 raised:
undefined method `show_all' for nil:NilClass
Is it my error in the link code? or Do I have to define something in the routes?
Thank you for your time and help

You cannot link directly to actions on controllers, you can only make requests which are connected to a controller/action via your routing table.
You need a route which will reach that action, and then you need a view which will render output to the user.

In your SylabusController:
def index
# are you sure that #topic is not null?
#questions = #topic.questions
end
In your view
<%= link_to 'All the questions', #questions, class: 'btn' %>
Just get class variable associateded with controller action :)

Related

Ruby on Rails -- independant controller method for static pages

So basically I want to use a simple controller method with no params:
def create_message
#a = Message.create(:body => "Hello")
#a.save
redirect_to messages_path
end
but i'm routing from the home page, pages controller:
def home
end
I'm having a problem figuring out what to write in the routes file, I've tried almost everything including but not limited to:
resources :pages do
collection do
get :create_message
end
end
Views:
<%= link_to "Create Message", create_message_pages_path, class:"btn btn-primary"%>
Error:
The action 'create_message' could not be found for PagesController
You can create custom route for create_message like this
#routes.rb
get 'create_message' => 'pages#create_message', as: 'create_message'
Then link_to would be:
#view
<%= link_to "Create Message", create_message_path, class:"btn btn-primary"%>
I faced this problem once, in my case it is defining action under private block of controller gave the "The Action could not be found error". From your question I see there is no problem in defining routes and using it in view file. Please check to see if the create_message action is defined under private block in pages_controller.rb file. Hope it helps.

Search box to find user in rails

I'm somewhat new to rails. I'm going through making the classic twitter clone right now. I want to have a search bar on my homepage that allows the user to search for a twitter handle, and if the handle exists, it will send the user to the show page for that twitter handle.
I've been following a RailsCast on how to implement a simple search, but instead of doing it on the index like the video, I want to do it on the show action. I've run into some problems though. The form sits on my user index view.
Here is the error:
ActionController::UrlGenerationError in Users#index
Showing c:/Sites/Projects/twitterapp/twitter/app/views/users/index.html.erb where line #2 raised:
No route matches {:action=>"show", :controller=>"users"} missing required keys: [:id]
Here is the form:
<%= form_tag(user_path, method: 'get') do %>
<%= text_field_tag(:search, params[:search]) %>
<%= submit_tag("Search", name: nil) %>
<% end %>
Here is my show action:
def show
#user = User.search(params[:search])
end
And here is my search method in my user model:
def self.search(search)
if search
find(:all, conditions:['name LIKE ?', "%#{search}%"])
else
find(:all)
end
end
Actually you cannot use the show method as a search result finder. Because according to the rails convention:
For any resource like users, rails scaffold generates index,new, show, create, update, delete methods based on your routes files.
Thus based on the conventional way, show method always asks for an object. Lets say you are using UserContoller show method. It asks for a user object. Which you haven't provide in the form. that's why :id missing error is given.
I would tell you to do some more learning. And for searching create a different method in a different controller and define that controller method to the routes.rb file. This is the best way to do.
If you still want to use the show method, then change the show methods routing from the routes.rb file. You've to manually declare the show action on routes file.
you are using user_path and path need to inform id from present user
you can do this in action :index but I recommend you to create a action to this
view
<%= form_tag(search_users_path, method: 'get') do %>
<%= text_field_tag(:search, params[:search]) %>
<%= submit_tag("Search", name: nil) %>
<% end %>
routes.rb
resources :users do
post 'search', :on => :collection
end
users_controller.rb
def search
#user = User.search(params[:search])
end
You should to create a view search.html.erb similar as index.html.erb
As Emu and Breno pointed what causing the problem user_path requires an user id
Solution idea:
Why not just point to users index action? like this:
<%= form_tag(users_path, method: 'get') do %>
<%= text_field_tag(:search, params[:search]) %>
<%= submit_tag("Search", name: nil) %>
<% end %>
users_controller.rb:
def index
if params[:search]
#user = User.search(params[:search])
end
end
and you can use ajax remote: true to handle the returned user object
Found your question via Google, but the responses and suggestions didn't work for me. Found another solution that did, so seems worth posting here.
"Search and Filter Rails Models Without Bloating Your Controller":
http://www.justinweiss.com/articles/search-and-filter-rails-models-without-bloating-your-controller/

Link to other pages wih same controller using Ruby on Rails

I am new to ruby on rails and stuck to very basic problem.I have created a controller named as custom_hello and define 2 methods. what i want is when i click on the link it will take me to next page which is under the same controller.i just don't know how to configure the routes properly.Any help would be appreciated...
Here it is:
app/controllers/custom_hello_controller.rb
class CustomHelloController < ApplicationController
def method1
end
def method2
end
end
config/routes.rb
get 'custom_hello/method1'
get 'custom_hello/method2'
Create 2 files in your views:
app/views/custom_hello/method1.html.erb
app/views/custom_hello/method2.html.erb
You can create links with:
<%= link_to 'Method 1', custom_hello_method1_path %>
<%= link_to 'Method 2', custom_hello_method2_path %>
However, you may consider creating RESTful controllers and routes. Please read here
<%= link_to 'link_name', :action => 'Your_method_name', :controller => 'custom_hello' %>
now you need to write 'custome_hello/Your_method_name' in your routes.rb and create Your_method_name.html.erb page in that controller when you click on link you will navigate to Your_method_name.html.erb page try it, this will work.

Undefined method 'model_name' when attempting to use Simple Form in Rails

I am attempting to get a form generated by simple-form in my modal, however I keep running into the following error upon loading the page.
undefined method 'model_name' for NilClass:Class
Here is the simple code I was using to try to generate the form
_header.html.erb (under the view_pages_controller)
<%= simple_form_for #update do |f| %>
<%= f.input :lang %>
<%= f.input :book %> #temp, just for testing simpform
<%= f.button :submit %>
<% end %>
I am pretty sure the problem lies with my controller code
updates_controller.rb
class UpdatesController < ApplicationController
before_filter :signed_in_user, only: [:create, :destroy]
def create
#update = current_user.updates.build(params[:update])
if #update.save
flash[:success] = "Update successful"
redirect_to root_path
else
flash[:error] = "Failed to update, please try again"
redirect_to root_path
end
end
end
update.rb
class Update < ActiveRecord::Base
attr_accessible :book, :user_id, :lang, :round_id
belongs_to :user
end
Any help/tips would be greatly appreciated. I know my code sucks.
The problem is that #update is null in your view. You should clarify which action renders this view, and set value to #update. The create action only sets it based on the params, and then redirects to root.
I believe you are using some kind of RESTfull controller, and you are rendering your form on action :new. So, to solve your trouble, add
#update = current_user.updates.build(params[:update])
to your new action
Have you tried putting a debugger in above the line in your controller where you declare #update.
You could then see your current_user object and what methods are available using something like current_user.methods
Have you included resource:'updates' or resources:'updates' in routes.rb.This may solve the problem.

Nested resource issue

I am struggling to pass an id successfully into my URL for the nested resource I have set up called Jobs.
The error I am getting when I try to pass the #job object into my link is as follows:
No route matches {:action=>"edit", :controller=>"jobs", :user_id=>1, :id=>nil}
Which clearly shows it can't find the id correctly and so is finding nil
At the moment I have my routes setup as so:
resources :users do
resources :jobs
end
and the link I have is <%= link_to "Edit", edit_user_job_path(#user.id,#job) %>
What is interesting is that if I pass the object #jobs with an 's' on the end it will load the page correctly but when I click on the link will try and add all of that users job id's.
In my controller for edit I have:
def edit
#user = current_user
#job = #user.jobs.find(params[:id])
end
Any help really would be much appreciated :)
UPDATE
Okay I was defining the object on the wrong page of my controller (under edit instead of index). The issue I am now having is Couldn't find Job without an ID
I updated my controller index definition to:
def index
#user = current_user
#jobs = #user.jobs.all
#job = #user.jobs.find(params[:id])
end
And have in my view (jobs#index)
<% #jobs.each do |f| %>
...
<%= link_to "Edit", edit_user_job_path(#user.id,job) %>
...
<% end %>
Any advice would be much appreciated if you know where I am going wrong :)
That error means that #job is nil.
The link is to the edit path, and the controller code you've provided is from the edit action in the controller. It seems unlikely that the edit page links to itself.
Look at the code that's actually rendering that page (it will appear in your stack trace) and you'll find that #job is not set. I suspect that you are on the index page and have something like:
<% #jobs.each do |job| %>
...
<%= link_to "Edit", edit_user_job_path(#user.id,#job) %>
...
<% end %>
If that is the case, then the link should be to job, not #job, i.e.
<%= link_to "Edit", edit_user_job_path(#user.id,job) %>
(expanding on iHiD's comment with his own post)
Using the restful resources means that you are going with the rails defaults, which consequently means that the index page gives you a list of all Jobs, and by default no single special job. If you run rake routes from the command line, you get all the routes, with parameters that are set from the URI. It should give you something like this:
user_jobs GET /users/:user_id/jobs(.:format) jobs#index
As you can see, there is no :id (params[:id]) for the index action.

Resources