Accessing first row in an object - ruby-on-rails

<% question = #questions.try(:first) %>
<h1><%= question.title %></h1>
I'm trying to use the above code to grab the first question from a Questions model, and then display it's title in HTML. However, I'm throwing the error undefined method 'title' for nil:NilClass
Autogenerated RoR files use the question.title line... why isn't it working here?

question.title raises error as undefined method 'title' for nil:NilClass that means question is set as nil. You set question using
<% question = #questions.try(:first) %>
It means either #questions is nil or there #questions.first returns nil.
Make sure that you set #questions instance variable in the Controller's action which renders this particular view.
def action_name
#questions = Question.all
end
Also, if you just want to show only the first question record in your view and you are not going to use #questions anywhere then just set
def action_name
#question = Question.first
end
and use it in the view directly as:
<h1><%= #question.try(:title) %></h1>

It looks like #question is nil. Have you assigned #question in your controller action. Can you show your code in your controller action?

Related

How to pass variable from controller to partial view file in rails?

I want to send a variable from controller to partial file.
My controller name is center_controller.rb and the partial file name is _view_center.html.erb.
In controller, I have #notes variable. When I give <%= #notes %>, Iam not getting the values,nil is coming. Can you help me on that?
center_controller.rb
def view
#notes = Notes.all render"view_center.html.erb"
end
and In my view_center.html.erb
<%= #notes %>
But Iam not getting #notes values, it is nil.
Thanks in Advance !!!
IMPORTANT UPDATE!
This is wrong
#notes = Notes.all
This is right
#notes = Note.all
Watch out ! When you call a class you want the class name in Singular
First of all you need to name the view to match the controller method.
View file names, by default, match the controller and action that they are tied to.
If you call your view (view_center.html.erb) you should name your controller method (view_center) example:
#center_controller.rb
def view_center
#notes = Note.all
end
#views/center/view_center.html.erb
<%= #notes %>
When you want to render a partial that uses a instance variable, you should do:
<%= render 'view_center', notes: #notes %>
The [notes: #notes] sends the variable to the partial
In the partial file you need to do this:
<% notes.each do |note| %>
<% end %>
Otherwise, take a look at Rails naming conventions, because usually, controller filenames are plural:
https://gist.github.com/iangreenleaf/b206d09c587e8fc6399e
centers_controller.rb
users_controller.rb
etc

Links with 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 :)

Kaminari & Rails pagination - undefined method `current_page'

I searched and searched, but nothing solved my problem. Here's my controller:
def show
#topic = Topic.find(params[:id])
#topic.posts = #topic.posts.page(params[:page]).per(2) # 2 for debugging
end
That functions just fine, because the topic view is reduced to two posts. However, when I add this to show.html.erb:
<%= paginate #topic.posts %>
I'm given this error:
undefined method `current_page' for #<ActiveRecord::Relation:0x69041c9b2d58>
Try with:
def show
#topic = Topic.find(params[:id])
#posts = #topic.posts.page(params[:page]).per(2)
end
And then:
<%= paginate #posts %>
If you get pagination errors in Kaminari like
undefined method `total_pages'
or
undefined method `current_page'
it is likely because the AR scope you've passed into paginate has not had the page method called on it.
Make sure you always call page on the scopes you will be passing in to paginate!
This also holds true if you have an Array that you have decorated using Kaminari.paginate_array
Bad:
<% scope = Article.all # You forgot to call page :( %>
<%= paginate(scope) # Undefined methods... %>
Good:
<% scope = Article.all.page(params[:page]) %>
<%= paginate(scope) %>
Or with a non-AR array of your own...
Bad:
<% data = Kaminari.paginate_array(my_array) # You forgot to call page :( %>
<%= paginate(data) # Undefined methods... %>
Again, this is good:
<% data = Kaminari.paginate_array(my_array).page(params[:page]) %>
<%= paginate(data) %>
Some time ago, I had a little problem with kaminari that I solved by using different variable names for each action.
Let's say in the index action you call something like:
def index
#topic = Topic.all.page(params[:page])
end
The index view works fine with <%= paginate #topic %> however if you want to use the same variable name in any other action, it throu an error like that.
def list
# don't use #topic again. choose any other variable name here
#topic_list = Topic.where(...).page(params[:page])
end
This worked for me.
Please, give a shot.

View inside other view

In a Rails application I have a view index.html.erb and a controller posts_controller.rb.
In the controller I have defined a variable:
def index
#posts = TableName.find...
and in the view I have:
<% #posts.each do |post| %>
If I access it via localhost/posts/index it works fine. But what I really want is to show this view inside other views so I'm using <%= render :template => 'posts/index' %> but I get this error message: "NoMethodError - You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.each"
How can I do this? Thanks
NoMethodError is triggered when you try to call methods on undefined object. In other word, you render posts/index in other views, but #posts instance variable is not defined in the other view. render template does not route the controller.

undefined method 'each' Ruby on Rails

Apologies in advance, I am a newbie trying to get my head around rails.
My View at the bottom works when I use:
def show
#posts = Post.all
end
However in my controller I now have:
def show
#posts = Post.find_by_category_id params[:id];
end
In my view I have
<%= #posts.each do |post| %>
<%= post.title %>
<% end %>
Some please explain why I get this error. What should I use. category_id is a foreign key on the Post table.
Look at http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-find_by
Finds the first record matching the specified conditions
find_by_ will return only one post, not a collection. So you are not able to use each.
try
def show
#posts = Post.all.find_by_category_id params[:id];
end

Resources