Can't Edit Item Error NoMethodError in Items#edit - ruby

I have an Item Model. Its for a retail store.
When im on an item view. Lets say for item id 11. Then i click on edit button. I receive the following error
Anyone have any clues? Any help would be greatly appreciated.
NoMethodError in Items#edit
undefined method `errors' for nil:NilClas
<% if #user.errors.any? %>
<div id="error_explanation">
<div class="alert alert-danger">
The form contains <%= pluralize(#user.errors.count, "error") %>.
</div>
<ul>
Below is where my edit button is in Item View
<!-- right column -->
<div class="col-lg-6 col-md-6 col-sm-5">
<div class = "itemtitle"><%= #item.title %> </div>
<div class = "price">$<%= #item.price %> </div>
<%= link_to "Edit Items", edit_item_path(#item) %>
<div class="productFilter productFilterLook2">
<div class="filterBox">
<select>
<option value="strawberries" selected>Quantity</option>
</select>
</div>
Here is my Items controller.
class ItemsController < ApplicationController
def index
#items = Item.paginate(page: params[:page])
end
def new
#item = Item.new
end
def edit
#item = Item.find(params[:id])
end
def show
#item = Item.find(params[:id])
end
def update
if #item.update(pin_params)
redirect_to #item, notice: 'Item was successfully updated.'
else
render action: 'edit'
end
end
def create
#item = current_user.items.build(item_params)
if #item.save
redirect_to #item
flash[:success] = "You have created a new item"
else
flash[:danger] = "Your item didn't save"
render "new"
end
end
def destroy
#item.destroy
respond_to do |format|
format.html { redirect_to items_url, notice: 'Item was successfully deleted' }
format.json { head :no_content }
end
end
private
def item_params
params.require(:item).permit(:title, :price, :description, :image)
end
end
_error_messages.html.erb
<% if #user.errors.any? %>
<div id="error_explanation">
<div class="alert alert-danger">
The form contains <%= pluralize(#user.errors.count, "error") %>.
</div>
<ul>
<% #user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>

You don't define #user in your edit action.
Probably somewhere in the template you render for the edit action you ask for #user.errors.any?. Either disable this part or modify to something like #item.errors.any? etc.

Related

undefined method `any?' for nil:NilClass for <% if #users.any? %>

I am following the Micheal Hartl Ruby on Rails tutorial. In the 12 chapter, I am getting this error.
I am trying to display the following and the followers, but I am not able to.
Following are the codes:
show.html.erb
<% provide(:title, #title) %>
<div class="row">
<aside class="col-md-4">
<section class="user_info">
<%= gravatar_for #user %>
<h1><%= #user.name %></h1>
<span><%= link_to "view my profile", #user %></span>
<span><b>Microposts:</b> <%= #user.microposts.count %></span>
</section>
<section class="stats">
<%= render 'shared/stats' %>
<% if #users.any? %>
<div class="user_avatars">
<% #users.each do |user| %>
<%= link_to gravatar_for(user, size: 30), user %>
<% end %>
</div>
<% end %>
</section>
</aside>
<div class="col-md-8">
<h3><%= #title %></h3>
<% if #users.any? %>
<ul class="users follow">
<%= render #users %>
</ul>
<%= will_paginate %>
<% end %>
</div>
</div>
relationship_controller.rb
class RelationshipsController < ApplicationController
before_action :logged_in_user
def create
def create
#user = User.find(params[:followed_id])
current_user.follow(user)
respond_to do |format|
format.html { redirect_to #user }
format.js
end
def destroy
#user = Relationship.find(params[:id]).followed
current_user.unfollow(user)
respond_to do |format|
format.html { redirect_to #user }
format.js
end
end
end
user_controller.rb
class UsersController < ApplicationController
before_action :logged_in_user, only: [:index, :edit, :update, :destroy,
:following, :followers]
before_action:correct_user, only: [:edit, :update]
before_action:admin_user, only: :destroy
def index
#users= User.paginate(page: params[:page])
end
def show
#user= User.find(params[:id])
#microposts = #user.microposts.paginate(page: params[:page], :per_page => 5)
end
def new
#user= User.new
end
def create
#user= User.new(user_params)
if #user.save
#user.send_activation_email
flash[:info] = "Please check your email to activate your account."
redirect_to root_url
else
render 'new'
end
end
def edit
#user= User.find(params[:id])
end
def update
#user= User.find(params[:id])
if #user.update_attributes(user_params)
flash[:success] = "Profile updated"
redirect_to #user
else
render 'edit'
end
end
def destroy
User.find(params[:id]).destroy
flash[:success] = "User deleted"
redirect_to users_url
end
def following
#title = "Following"
#user = User.find(params[:id])
#users = #user.following.paginate(page: params[:page])
render 'show_follow'
end
def followers
#title = "Followers"
#user = User.find(params[:id])
#users = #user.followers.paginate(page: params[:page])
render 'show_follow'
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
def correct_user
#user= User.find(params[:id])
redirect_to(root_url) unless #user== current_user
end
def admin_user
redirect_to(root_url) unless current_user.admin?
end
end
Your issue is that the show action is actually using the #user instead of #users instance variable.
Your section for stats will not work since it's expecting what it looks like a collection of User as it would from the index action.
Since you have the action for followers which sets the #user and #users instance variables you have to visit that action instead and the code on your show.html.erb template will most likely have to move to the show_follow.html.erb template.
UPDATE
You need to remove this section from your show.html.erb template
<section class="stats">
<%= render 'shared/stats' %>
<% if #users.any? %>
<div class="user_avatars">
<% #users.each do |user| %>
<%= link_to gravatar_for(user, size: 30), user %>
<% end %>
</div>
<% end %>
</section>
</aside>
<div class="col-md-8">
<h3><%= #title %></h3>
<% if #users.any? %>
<ul class="users follow">
<%= render #users %>
</ul>
<%= will_paginate %>
<% end %>
</div>
I saw your repository and seems like you have messed up the code, according to what you are following(Ruby on Rails - Micheal Hartl), this is what you need to change:
The code in your show.html.erb should be placed in show_follow.html.erb
After this follow the 12th chapter again and place the right code in show.html.erb.

Display data according to text field value using Rails 3

I have a issue.I want to fetch data from data base according to text field value.This text field will take two types of value.First one is simple number(e.g-123456789) and second one is like this(e.g-123456789/1).The simple number is present in DB for one table.In the second one number after "/" (i.e-1) is another table's id which is associated with first table.Then my aim is when user will give the input "123456789" the data will fetch according to this number by searching and when user will give the input "123456789/1" first it will split the number and values will be fetched according to both number and id (i.e-123456789 and 1) from the both table.
Here i am explaining some of my code below.
homes/hcsy_html.erb
<% if current_admin %>
<div class="header">
<div class="navbar-header">Swargadwar, Puri Municipality,govt of odisha</div>
<div class="nav navbar-top-links navbar-right">
<div class="image"></div>
</div>
<div class="name-div">
</div>
</div>
<div class="menu-div">
<div id="leftsidebtn">
<ul>
<li>Create User</li>
<li>Scan Report</li>
<li>View and Payment Report
<ul>
<li>HCSY</li>
</ul>
</li>
<li>Payment Validate</li>
<li>Log Out</li>
</ul>
</div>
</div>
<div class="content-div">
Logged in as:<%= current_admin.email %>
<center><h1>HARICHANDRA SAHAYATA YOJANA SLIP</h1></center>
<%= form_for :hcsy,:url => {:action =>'scan_hcsy' } do |f| %>
<%= f.text_field :reciept,placeholder:"Get your scan code",:onchange => 'this.form.submit();' %>
<% end %>
<% if params[:id] %>
<center><h1>HARICHANDRA SAHAYATA YOJANA SLIP</h1></center>
Receipt No :<%= #hcsys.Receipt_No %>
<div class="left-content">
<p>Deceased Name :</p> <%= #hcsys.Deceased_Name %>
<p>Beneficary name :</p> <%= #hcsys.Beneficiary_Name %>
<p>Relation with Deceased :</p> <%= #hcsys.Beneficiary_Rel_With_Decease %>
<p>Address :</p> <%= #hcsys.Address %>
<p>Police station :</p> <%= #hcsys.PoliceStation %>
<p>Mobile No :</p> <%= #hcsys.Mobile_No %>
<p>Occupation :</p> <%= #hcsys.Occupation %>
<p>Brahmin :</p> <%= #hcsys.Brahmin %>
<p>Amount Required :</p> <%= #hcsys.Amount_Required %>
<p>Has He/She recieved any assistance erlier from this fund :</p> <%= #hcsys.Recieved_Fund_Earlier %>
</div>
<div class="right-content">
<p>BPL :</p> <%= #hcsys.BPL %>
<p>Govt. Service :</p> <%= #hcsys.Govt_Service %>
<p>Business :</p> <%= #hcsys.Business %>
<p>Land of property :</p> <%= #hcsys.Land_Property %>
<p>Other :</p> <%= #hcsys.Others %>
</div>
<% end %>
</div>
<% end %>
controller/homes_controller.rb
class HomesController < ApplicationController
def index
end
def registration
#user=User.new
end
def usersave
#admin=Admin.find(params[:id])
#user=User.new(params[:user])
#user.admin_id=#admin.id
if #user.save
flash[:notice]="User has created successfully"
flash[:color]="valid"
redirect_to :action => "index"
else
flash[:alert]="User could not created"
flash[:color]="invalid"
render 'registration'
end
end
def hcsy_reg
#hcsy=THcsy.new
end
def create_reg
#hcsy=THcsy.new(params[:hcsy])
if #hcsy.save
flash[:notice]="Data has saved successfully"
flash[:color]="valid"
redirect_to :action => "hcsy_details",:id1 => params[:id],:id2 => #hcsy.id
else
flash[:alert]="Data could not saved successfully"
flash[:color]="invalid"
render 'hcsy_reg'
end
end
def scan_hcsy
#hcsy=THcsy.find_by_Receipt_No(params[:hcsy][:reciept])
if #hcsy
flash[:notice]="Check the record"
flash[:color]="valid"
redirect_to :action => 'hcsy',:id => #hcsy.id
else
flash[:alert]="Receipt number could not found"
flash[:color]="invalid"
render 'hcsy'
end
end
def hcsy
if params[:id]
#hcsys=THcsy.find(params[:id])
end
end
def scanrecord
#hcsy=THcsy.find(params[:id])
end
def hcsy_deatils
#t_hcsy=THcsyFundTypeMaster.new
end
def create_details
#t_hcsy=THcsyFundTypeMaster.new(params[:t_hcsy])
if #t_hcsy.save
flash[:notice]="Check the record"
flash[:color]="valid"
redirect_to :action => 'hcsy_details_master',:id1 => params[:id1] ,:id2 => params[:id2] , :id3 => #t_hcsy.HCSY_Fund_Type_ID
else
flash[:alert]="Receipt number could not found"
flash[:color]="invalid"
render 'hcsy_deatils'
end
end
def hcsy_details_master
#t_hcsy_master=THcsyDetails.new
end
def create_details1
#admin=Admin.find(params[:id1])
#hcsy=THcsy.find(params[:id2])
#t_hcsy=THcsyFundTypeMaster.find_by_HCSY_Fund_Type_ID(params[:id3])
#t_hcsy_master=THcsyDetails.new(params[:t_hcsy_master])
#t_hcsy_master.Created_By=#admin.id
#t_hcsy_master.HCSY_ID=#hcsy.id
#t_hcsy_master.HCSY_Fund_Type_ID=#t_hcsy.HCSY_Fund_Type_ID
if #t_hcsy_master.save
flash[:notice]="Record has created"
flash[:color]="valid"
redirect_to :action => 'index'
else
flash[:alert]="Record could not create"
flash[:color]="invalid"
render 'hcsy_details_master'
end
end
end
Here i have done for simple number please help me to fetch data from both table by the second input number(i.e-123456789/1).For this all operations are executing inside "scan_hcsy" method.Atleast help me to split the number(i.e-123456789/1) to 123456789 and 1 so that i can fetch data according to this number and id.
You can split the string, which results into an Array:
"12345678/1".split('/')
=> ["12345678", "1"]
In your case:
splitted = params[:hcsy][:reciept].split('/')
hcys = splitted[0]
table_id = splitted[1]

Getting undefined method `[]' for nil:NilClass in Rails 3

I want to fetch text field value to my controller and do the search with database but i got the following error.
Error:
NoMethodError in HomesController#scan_hcsy
undefined method `[]' for nil:NilClass
Rails.root: C:/Site/swargadwar
Application Trace | Framework Trace | Full Trace
app/controllers/homes_controller.rb:38:in `scan_hcsy'
Please check my below code and try to resolve this error.
homes/hcsy_html.erb
<% if current_admin %>
<div class="header">
<div class="navbar-header">Swargadwar, Puri Municipality,govt of odisha</div>
<div class="nav navbar-top-links navbar-right">
<div class="image"></div>
</div>
<div class="name-div">
</div>
</div>
<div class="menu-div">
<div id="leftsidebtn">
<ul>
<li>Create User</li>
<li>Scan Report</li>
<li>View and Payment Report
<ul>
<li>HCSY</li>
</ul>
</li>
<li>Payment Validate</li>
<li>Log Out</li>
</ul>
</div>
</div>
<div class="content-div">
Logged in as:<%= current_admin.email %>
<center><h1>HARICHANDRA SAHAYATA YOJANA SLIP</h1></center>
<%= form_for :hcsy,:url => {:action =>'scan_hcsy' } do |f| %>
<%= f.text_field :reciept,placeholder:"Get your scan code" %>
<%= f.submit "search" %>
<% end %>
</div>
<% end %>
controller/homes_controller.rb
class HomesController < ApplicationController
def index
end
def registration
#user=User.new
end
def usersave
#admin=Admin.find(params[:id])
#user=User.new(params[:user])
#user.admin_id=#admin.id
if #user.save
flash[:notice]="User has created successfully"
flash[:color]="valid"
redirect_to :action => "index"
else
flash[:alert]="User could not created"
flash[:color]="invalid"
render 'registration'
end
end
def hcsy_reg
#hcsy=THcsy.new
end
def create_reg
#hcsy=THcsy.new(params[:hcsy])
if #hcsy.save
flash[:notice]="Data has saved successfully"
flash[:color]="valid"
redirect_to :action => "index"
else
flash[:alert]="Data could not saved successfully"
flash[:color]="invalid"
render 'hcsy_reg'
end
end
def scan_hcsy
#hcsy=THcsy.find_by_Receipt_No(params[:hcsy][:receipt])
if #hcsy
flash[:notice]="Check the record"
flash[:color]="valid"
redirect_to :action => 'scanrecord'
else
flash[:alert]="Receipt number could not found"
flash[:color]="invalid"
render 'hcsy'
end
end
def hcsy
#hcsy=THcsy.new
end
def scan_record
end
end
model/t_hcsy.rb
class THcsy < ActiveRecord::Base
attr_accessible :Address, :Amount_Required, :B_Audio, :B_Thumb, :B_photo, :Beneficiary_Name, :Beneficiary_Rel_With_Decease, :Brahmin, :Business, :Created_by, :D_photo, :Date_Of_Required, :Deceased_Name, :Govt_Service, :HCSY_ID, :Land_Property, :Mobile_No, :Occupation, :Others, :PoliceStation, :Prev_Amount_Received, :Prev_Date_Recieved, :Prev_Receipt_No, :Receipt_No, :Recieved_Fund_Earlier, :Sdp_Id, :Updated_By,:BPL
attr_accessor :receipt
end
Please help me.
You have a problem with your params.
Try adding some debugging code, such as:
def scan_hcsy
+ raise ArgumentError if params.nil?
+ raise ArgumentError if params[:hcsy].nil?
+ raise ArgumentError if params[:hcsy][:receipt].nil?
Try fixing this spelling:
- <%= f.text_field :reciept, ...
+ <%= f.text_field :receipt, ...

group_by posts by day and then date with different div

I have the following in my index action of posts controller:
#posts = Post.all.order("created_at DESC")
In my view like:
<% #posts.each do |post| %>
<%= post.title %>
<% end %>
I want to group the posts by day and then the date like the following:
Tuesday (date)
Sports
World
Politics
Monday (date)
Sports
Catering
I just want to have the day and date in separate div's:
(<div>
<%= day %>
</div>
<div>
<%= date %>
</div>)
I am using PostgreSQL.
UPDATE
create.js.erb
$("#post_table").html("<%= escape_javascript(render('posts/post')) %>")
$modal.modal("hide");
posts_controller:
before_action :all_posts, only: [:index, :new, :create]
def create
#post = Post.new(post_params)
#post.user_id = current_user.id
respond_to do |format|
if #post.save
format.html { redirect_to root_path }
format.js
flash[:notice] = "Successfully created post."
else
format.html { render action: 'new' }
format.js
end
end
end
private
def all_posts
#posts = Post.all.order("created_at DESC")
#post_groups=#posts.group_by{|post| [post.created_at.wday,post.created_at.to_date]}
end
index.html.erb
<% #post_groups.each do |group,posts| %>
<% day = group[1].strftime("%A") %>
<% date = group[1].strftime("#{group[1].day.ordinalize}" " %B " " %Y") %>
<div class="sort_by_date">
<span class="sort_by_post_day">
<%= day %>
</span>
<span class="sort_by_post_ordinals">
<%= date %>
</span>
</div>
<div id="post_table">
<%= render 'post', posts: #posts %>
</div>
<% end %>
Update is working fine, but whenever create a new post the refresh part is not working. it refresh but I could see the new post after I reload my website.
Thanks
controller
#post_groups=Post.order('created_at DESC').group_by{|post| [post.created_at.wday,post.created_at.to_date]}
View
<% #post_groups.each do |group,posts| %>
<%day=group[1].strftime("%A")%>
<%date=group[1].to_s%>
<div>
<%=day%>
</div>
<div>
<%=date%>
</div>
<br>
<%posts.each do |post|%>
<div><%=post.title%></div>
<%end%>
<hr>
<% end %>
In here I grouped all the posts by weekday and then group them with date.
This will return the hash of all the grouped data. hash key will be an array of format
[weekday,date] and value for this key will be an array of Posts which comes to this group and i am showing them in view according.
You can fiddle around view to change the styling according to your requirement.

Email validation message Rails and foundation

I am trying to display a message using foundation framework to validate and add email address.The validation happens as expected, but no messages get displayed. Is there something I am missing?
_messages.html.erb
<% flash.each do |name, msg| %>
<% if msg.is_a?(String) %>
<div data-alert class="alert-box round <%= name.to_s == :notice ? "success" : "alert" %>">
<%= content_tag :div, msg %>
×
</div>
<% end %>
<% end %>
contacts_controller.rb
class ContactsController < ApplicationController
def new
#contact = Contact.new
end
def create
#contact = Contact.new(secure_params)
if #contact.valid?
#contact.update_spreadsheet
flash[:notice] = 'You have been added'
redirect_to root_path
else
flash.now[:alert] = 'Not a valid email'
redirect_to root_path
end
end
private
def secure_params
params.require(:contact).permit(:email)
end
end
application.html.erb
<header>
<%= render 'layouts/navigation' %>
</header>
<%= render 'layouts/messages' %>
<%= yield %>
</body>
</html>
Within messages partial _messages.html.erb, you are comparing a string to a symbol which is the reason the message is not displayed.
name.to_s is an object of String class and
:notice is an object of Symbol class
Problem line:
<div data-alert class="alert-box round <%= name.to_s == :notice ? "success" : "alert" %>">
You should match name.to_s == "notice" here
The issue was indeed with the _messages partial
changed
<div data-alert class="alert-box round <%= name.to_s == :notice ? "success" : "alert" %>">
to
<div data-alert class="alert-box round <%= name.to_s == 'notice' ? 'success' : 'alert' %>">
and all worked as expected.

Resources