rails 4 - undefined method `group_by' for nil:NilClass - ruby-on-rails

i am getting an error i do not seem to understand. Any help would be much appreciated.
I have a list of users but wanted to display only users that have created events using the inbuilt ruby function 'group_by'. but i get the error "undefined method `group_by' for nil:NilClass"
The console:
Started GET "/users" for 127.0.0.1 at 2014-12-24 15:54:01 +0000
Processing by UsersController#index as HTML
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = 40 ORDER BY "users"."id" ASC LIMIT 1
Rendered users/index.html.erb within layouts/application (1.1ms)
Completed 500 Internal Server Error in 5ms
ActionView::Template::Error (undefined method `group_by' for nil:NilClass):
10: </tr>
11:
12:
13: <% #events.group_by(&:user).each do |user, events| %>
14: <%= link_to(image_tag("profile_image_gravatar.png"), user) %>
15: <%= user.full_name %>
16: <%= link_to 'Show', user %>
app/views/users/index.html.erb:13:in `_app_views_users_index_html_erb__3564202377022035077_70335954377780'
Rendered /Users/ARTLoe/.rvm/gems/ruby-2.1.2/gems/actionpack-4.1.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (1.3ms)
Rendered /Users/ARTLoe/.rvm/gems/ruby-2.1.2/gems/actionpack-4.1.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.0ms)
Rendered /Users/ARTLoe/.rvm/gems/ruby-2.1.2/gems/actionpack-4.1.1/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb within rescues/layout (9.5ms)
events_controller.rb
class EventsController < ApplicationController
before_action :set_event, only: [:show, :edit, :update, :destroy]
before_filter :authenticate_user!
def index
#events = Event.order(:date)
# #events = current_user.events | displays only events by current user
end
def show
#commentable = #event
#comments = #commentable.comments
#comment = Comment.new
end
def new
#event = Event.new
end
def edit
end
def create
#event = Event.new(event_params)
#event.user = current_user
respond_to do |format|
if #event.save
format.html { redirect_to #event, notice: 'Event was successfully created.' }
format.json { render :show, status: :created, location: #event }
else
format.html { render :new }
format.json { render json: #event.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #event.update(event_params)
format.html { redirect_to #event, notice: 'Event was successfully updated.' }
format.json { render :show, status: :ok, location: #event }
else
format.html { render :edit }
format.json { render json: #event.errors, status: :unprocessable_entity }
end
end
end
def destroy
#event.destroy
respond_to do |format|
format.html { redirect_to events_url, notice: 'Event was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_event
#event = Event.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def event_params
params.require(:event).permit(:name, :description, :date, :time, :city, :price, :user_id)
end
end
users_controller.rb
class UsersController < ApplicationController
before_action :set_user, only: [:show]
before_filter :authenticate_user!
def index
#users = User.all
end
def show
#user = User.find(params[:id])
#user_events = #user.events.order(:date)
#events = Event.all
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
#user = User.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:email, :password, :password_confirmation, :firstname, :lastname, :dob, :gender, :description, :role)
end
end
users/index.html.erb
<% provide(:title, 'Users') %>
<h1>Listed Event Organizers</h1>
<% #events.group_by(&:user).each do |user, events| %>
<%= link_to(image_tag("profile_image_gravatar.png"), user) %>
<%= user.full_name %>
<%= link_to 'Show', user %>
<% end %>
<h6><%= link_to 'Create Event', new_event_path %></h6>

You're not defining #events in UsersController#index.

Your action isn't defining the instance variable that you're trying to use in the view.
In your index action within the UsersController, you need to define the #events variable.
Something like in the index action of your EventsController
class class UsersController < ApplicationController
def index
#users = User.all
#events = Event.includes(:user)
end
end

Related

Rails join table not saving

Hi I am playing around in rails and have built a little listing application.
My application has a listing model that has many tags through a has and belongs to many join table.
the join table is called listings_tags
The problem I have is that I cannot save the listing_tag association during create or update.
I can see in console
Started PATCH "/listings/92" for 127.0.0.1 at 2018-08-15 12:45:58 +1000
Processing by ListingsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"5isdLs2FiToZxtm1ZVPP0y0lKtnfyoLA8Njv4GBwWVH1M3TIm2IUW9ts5RR06OpQz8tgSBitZ7Rm69uVIifevQ==", "listing"=>{"name"=>"Canteen Coffee", "streetAddres"=>"19 Park Avenue", "suburb_id"=>"31", "post_code_id"=>"2", "region_id"=>"1", "country_id"=>"2", "telephone"=>"+61416650204", "url"=>"http://canteencoffee.com.au/canteen-kitchen/", "tag_ids"=>["", "1"]}, "commit"=>"Update Listing", "id"=>"92"}
Listing Load (0.2ms) SELECT "listings".* FROM "listings" WHERE "listings"."id" = $1 LIMIT $2 [["id", 92], ["LIMIT", 1]]
Unpermitted parameter: :tag_ids
(1.8ms) BEGIN
Suburb Load (5.4ms) SELECT "suburbs".* FROM "suburbs" WHERE "suburbs"."id" = $1 LIMIT $2 [["id", 31], ["LIMIT", 1]]
(1.7ms) COMMIT
Redirected to http://localhost:3000/listings/92
Completed 302 Found in 21ms (ActiveRecord: 9.0ms)
Obviously my issue is the :tag_ids
so I tried changing my listing params.require(:listing).permit() to include listing_attributes: [:id], tags: [:id] and :tag_ids
its killing me :) please help
Listing Model
class Listing < ApplicationRecord
has_and_belongs_to_many :tags
belongs_to :suburb
has_one :post_code, through: :suburb
accepts_nested_attributes_for :tags
def self.search(term)
if term
where('name LIKE ?', "%#{term}%")
else
order('id DESC')
end
end
end
Tag Model
class Tag < ApplicationRecord
has_and_belongs_to_many :listings
end
Listings Tags Schema
create_table "listings_tags", id: false, force: :cascade do |t|
t.bigint "listing_id", null: false
t.bigint "tag_id", null: false
t.index ["listing_id", "tag_id"], name: "index_listings_tags_on_listing_id_and_tag_id"
end
Listings Controller
class ListingsController < ApplicationController
before_action :set_listing, only: [:show, :edit, :update, :destroy]
# GET /listings
# GET /listings.json
def index
#listings = Listing.search(params[:term])
end
# GET /listings/1
# GET /listings/1.json
def show
#listing = Listing.find(params[:id])
#tags = #listing.tags
#suburb = #listing.suburb
#postcode = #suburb.post_code
end
# GET /listings/new
def new
#listing = Listing.new
end
# GET /listings/1/edit
def edit
end
# POST /listings
# POST /listings.json
def create
#listing = Listing.new(listing_params)
respond_to do |format|
if #listing.save
format.html { redirect_to #listing, notice: 'Listing was successfully created.' }
format.json { render :show, status: :created, location: #listing }
else
format.html { render :new }
format.json { render json: #listing.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /listings/1
# PATCH/PUT /listings/1.json
def update
respond_to do |format|
if #listing.update(listing_params)
format.html { redirect_to #listing, notice: 'Listing was successfully updated.' }
format.json { render :show, status: :ok, location: #listing }
else
format.html { render :edit }
format.json { render json: #listing.errors, status: :unprocessable_entity }
end
end
end
# DELETE /listings/1
# DELETE /listings/1.json
def destroy
#listing.destroy
respond_to do |format|
format.html { redirect_to listings_url, notice: 'Listing was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_listing
#listing = Listing.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def listing_params
params.require(:listing).permit(:name, :streetAddress, :telephone, :url, :term, :suburb_id, :post_code_id, :region_id, :country_id, :tag_ids)
end
end
Tags Controller
class TagsController < ApplicationController
before_action :set_tag, only: [:show, :edit, :update, :destroy]
# GET /tags
# GET /tags.json
def index
#tags = Tag.all
end
# GET /tags/1
# GET /tags/1.json
def show
#tag = Tag.find(params[:id])
#listings = #tag.listings
end
# GET /tags/new
def new
#tag = Tag.new
end
# GET /tags/1/edit
def edit
end
# POST /tags
# POST /tags.json
def create
#tag = Tag.new(tag_params)
respond_to do |format|
if #tag.save
format.html { redirect_to #tag, notice: 'Tag was successfully created.' }
format.json { render :show, status: :created, location: #tag }
else
format.html { render :new }
format.json { render json: #tag.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /tags/1
# PATCH/PUT /tags/1.json
def update
respond_to do |format|
if #tag.update(tag_params)
format.html { redirect_to #tag, notice: 'Tag was successfully updated.' }
format.json { render :show, status: :ok, location: #tag }
else
format.html { render :edit }
format.json { render json: #tag.errors, status: :unprocessable_entity }
end
end
end
# DELETE /tags/1
# DELETE /tags/1.json
def destroy
#tag.destroy
respond_to do |format|
format.html { redirect_to tags_url, notice: 'Tag was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_tag
#tag = Tag.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def tag_params
params.require(:tag).permit(:name)
end
end
Form
<%= bootstrap_form_for(#listing, local: true) do |form| %>
<%= form.text_field :name, id: :listing_name %>
<%= form.text_field :streetAddress, id: :listing_streetAddress %>
<%= form.collection_select(:suburb_id, Suburb.all, :id, :name) %>
<%= form.collection_select(:post_code_id, PostCode.all, :id, :number) %>
<%= form.collection_select(:region_id, Region.all, :id, :name) %>
<%= form.collection_select(:country_id, Country.all, :id, :name) %>
<%= form.text_field :telephone, id: :listing_telephone %>
<%= form.text_field :url, id: :listing_url %>
<%= form.select :tag_ids, Tag.all.pluck(:name, :id), {}, { multiple: true, class: "selectize" } %>
<%= form.submit %>
<% end %>
I really appreciate your help. I am sure it is probably something simple that I am doing wrong.
try this
params.require(:listing).permit(:name, :streetAddress, :telephone, :url, :term, :suburb_id, :post_code_id, :region_id, :country_id, :tag_ids => [])
source : https://github.com/rails/strong_parameters

Rails model form f.select do not assign selected value to model key

sorry for this question but I'm struggling with this issue for hours now and can't find the answer anywhere.
Here is the thing, I have a rails app with "Reservation" and "Space" models with the following relations:
class Reservation < ActiveRecord::Base
belongs_to :space
belongs_to :user
end
class Space < ActiveRecord::Base
belongs_to :condo
has_many :reservations
end
When the user creates a new Reservation, in the form he gets to choose from a dropdown (f.select) the spaces available for him. The f.select in the form look like this:
<div class="field">
<%= #user_spaces = current_user.condo.spaces
f.select :space_id,
options_from_collection_for_select(#user_spaces, :id, :name), :prompt => "Select space"
%>
</div>
That select it supose to assign a value to the key "space_id" in the Reservation that is being created (column's table is created). But when I check the last reservation in Rails console, space_id value is "nil". What am I doing wrong?
Thank you very much for your help
Reservation controller file:
class ReservationsController < ApplicationController
before_action :set_reservation, only: [:show, :edit, :update, :destroy]
# GET /reservations
# GET /reservations.json
def index
#reservations = Reservation.all
end
# GET /reservations/1
# GET /reservations/1.json
def show
end
# GET /reservations/new
def new
#reservation = Reservation.new
end
# GET /reservations/1/edit
def edit
end
# POST /reservations
# POST /reservations.json
def create
#reservation = Reservation.new(reservation_params)
#user = current_user.id
#reservation.user_id = #user
respond_to do |format|
if #reservation.save
format.html { redirect_to #reservation, notice: 'Reservation was successfully created.' }
format.json { render :show, status: :created, location: #reservation }
else
format.html { render :new }
format.json { render json: #reservation.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /reservations/1
# PATCH/PUT /reservations/1.json
def update
respond_to do |format|
if #reservation.update(reservation_params)
format.html { redirect_to #reservation, notice: 'Reservation was successfully updated.' }
format.json { render :show, status: :ok, location: #reservation }
else
format.html { render :edit }
format.json { render json: #reservation.errors, status: :unprocessable_entity }
end
end
end
# DELETE /reservations/1
# DELETE /reservations/1.json
def destroy
#reservation.destroy
respond_to do |format|
format.html { redirect_to reservations_url, notice: 'Reservation was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_reservation
#reservation = Reservation.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def reservation_params
params.require(:reservation).permit(:eventdate)
end
end
Space controller file:
class SpacesController < ApplicationController
before_action :set_space, only: [:show, :edit, :update, :destroy]
# GET /spaces
# GET /spaces.json
def index
#spaces = Space.all
end
# GET /spaces/1
# GET /spaces/1.json
def show
end
# GET /spaces/new
def new
#space = Space.new
end
# GET /spaces/1/edit
def edit
end
# POST /spaces
# POST /spaces.json
def create
#space = Space.new(space_params)
respond_to do |format|
if #space.save
format.html { redirect_to #space, notice: 'Space was successfully created.' }
format.json { render :show, status: :created, location: #space }
else
format.html { render :new }
format.json { render json: #space.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /spaces/1
# PATCH/PUT /spaces/1.json
def update
respond_to do |format|
if #space.update(space_params)
format.html { redirect_to #space, notice: 'Space was successfully updated.' }
format.json { render :show, status: :ok, location: #space }
else
format.html { render :edit }
format.json { render json: #space.errors, status: :unprocessable_entity }
end
end
end
# DELETE /spaces/1
# DELETE /spaces/1.json
def destroy
#space.destroy
respond_to do |format|
format.html { redirect_to spaces_url, notice: 'Space was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_space
#space = Space.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def space_params
params.require(:space).permit(:name)
end
end
And full Reservation Form:
<%= form_for(#reservation) do |f| %>
<% if #reservation.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#reservation.errors.count, "error") %> prohibited this reservation from being saved:</h2>
<ul>
<% #reservation.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :eventdate %><br>
<%= f.date_select :eventdate %>
</div>
<div class="field">
<%= #user = current_user.condo.spaces
f.select :space_id,
options_from_collection_for_select(#user, :id, :name), :prompt => "Select space"
%>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
pretty sure you need to permit the space_id attribute in your strong params.
def reservation_params
params.require(:reservation).permit(:eventdate, :space_id)
end
whats happening is that when you go to create a reservation, youre passing in set of params, that is the output of reservation_params
#reservation = Reservation.new(reservation_params)
if space_id is not being permitted in your strong params, then it will be nil when created.
if this is not the issue, can you post what params are getting to the server, and what the output of reservation_params are.

Rails 4: Unable to create checkout

I'm having a hard time implementing a checkout process where once at the cart, user can checkout and have order shipped. Maybe I need an order model and transaction controller?
I'm just not sure how to set those up. Currently the cart works and can be cleared as well as have items be added, its just I'm not sure how to implement a checkout and order system.
Idea is: User at cart clicks the checkout button, then is taken to checkout where he/she can input payment information, then taken back to products page. Issue is I'm not sure again how to connect the cart to the checkout and payment process into one simple easy system.
Any help would be appreciated, I'm still very new at this. Thank you.
class CartController < ApplicationController
before_action :authenticate_user!, except: [:index]
def add
id = params[:id]
if session[:cart] then
cart = session[:cart]
else
session[:cart] = {}
cart = session[:cart]
end
if cart[id] then
cart[id] = cart[id] + 1
else
cart[id] = 1
end
redirect_to :action => :index
flash[:notice] = 'added to cart'
end
def clearCart
session[:cart] = nil
redirect_to :action => :index
flash[:notice] = 'cart cleared'
end
def index
if session[:cart] then
#cart = session[:cart]
else
#cart = {}
end
end
end
class ProductsController < ApplicationController
before_action :set_product, only: [:show, :edit, :update, :destroy]
def index
#products = Product.all
end
def show
end
def new
#product = Product.new
end
def edit
end
def create
#product = Product.new(product_params)
respond_to do |format|
if #product.save
format.html { redirect_to #product, notice: 'Product was successfully created.' }
format.json { render :show, status: :created, location: #product }
else
format.html { render :new }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #product.update(product_params)
format.html { redirect_to #product, notice: 'Product was successfully updated.' }
format.json { render :show, status: :ok, location: #product }
else
format.html { render :edit }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
def destroy
#product.destroy
respond_to do |format|
format.html { redirect_to products_url, notice: 'Product was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_product
#product = Product.find(params[:id])
end
def product_params
params.require(:product).permit(:title, :description, :price, :category, :subcategory)
end
end
class Product < ActiveRecord::Base
end
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
views/cart/index.html.erb
<h1>Your Cart</h1>
<% if #cart.empty? %>
<p> Your cart is currently empty</p>
<% else %>
<%= link_to 'Empty your Cart', cart_clear_path %>
<br><br>
<% end %>
<% total = 0 %>
<ul>
<% #cart.each do | id, quantity | %>
<% product = Product.find_by_id(id) %>
<li>
<%= link_to product.title, product %>
<p><%= product.description %></p>
<p><%= number_to_currency product.price %></p>
<p>Quantity: <%= quantity %></p>
</li>
<% total += quantity * product.price %>
<% end %>
<p><b><%= number_to_currency total, :unit => '$' %> </b></p>
</ul>
What I've tried below
order.rb
class Order < ActiveRecord::Base
belongs_to :cart
end
cart.rb
class Cart < ActiveRecord::Base
has_many :line_items
has_one :order
end
Orders_Controller.rb
class OrdersController < ApplicationController
before_action :set_order, only: [:show, :edit, :update, :destroy]
# GET /orders
# GET /orders.json
def index
#orders = Order.all
end
# GET /orders/1
# GET /orders/1.json
def show
end
# GET /orders/new
def new
#order = Order.new
end
# GET /orders/1/edit
def edit
end
# POST /orders
# POST /orders.json
def create
#order = Order.new(order_params)
respond_to do |format|
if #order.save
format.html { redirect_to #order, notice: 'Order was successfully created.' }
format.json { render :show, status: :created, location: #order }
else
format.html { render :new }
format.json { render json: #order.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /orders/1
# PATCH/PUT /orders/1.json
def update
respond_to do |format|
if #order.update(order_params)
format.html { redirect_to #order, notice: 'Order was successfully updated.' }
format.json { render :show, status: :ok, location: #order }
else
format.html { render :edit }
format.json { render json: #order.errors, status: :unprocessable_entity }
end
end
end
# DELETE /orders/1
# DELETE /orders/1.json
def destroy
#order.destroy
respond_to do |format|
format.html { redirect_to orders_url, notice: 'Order was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_order
#order = Order.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def order_params
params.require(:order).permit(:new, :cart_id, :ip_address, :first_name, :last_name, :user_id)
end
end
added Checkout to views/cart/index.html.erb
<%= link_to "Checkout", new_order_path, class: "btn btn-primary" %>
What do I do after this?
you've used a local variable product, not the controller attribute #product. (just add the '#' sign)
my advise to you is to use a gem like shoppe,
you can see example here (demo)
you can also navigate through the models of the gem to see how they did it, maybe it will give you a clear perspective of writing an e-commerce solution.

Facing error while using render in rails

I am having 2 models:
app/models/employee.rb:
class Employee < User
has_many :insurances
end
app/models/insurance.rb:
class Insurance < ActiveRecord::Base
belongs_to :employee
end
app/controllers/employees_controller.rb:
class EmployeesController < ApplicationController
before_action :set_employee, only: [:show, :edit, :update, :destroy]
before_action :employee_params, only: [:create, :update]
# GET /employees
# GET /employees.json
def index
#employees = Employee.all
end
# GET /employees/1
# GET /employees/1.json
def show
#employee = Employee.find(params[:id])
end
# GET /employees/new
def new
#employee = Employee.new
end
# GET /employees/1/edit
def edit
#employee = Employee.find(params[:id])
end
# POST /employees
# POST /employees.json
def create
#employee = Employee.new(employee_params)
respond_to do |format|
if #employee.save
format.html { redirect_to employees_url, notice: "#{#employee.first_name} was successfully created." }
format.json { render :index, status: :created, location: #employee }
else
format.html { render :new }
format.json { render json: #employee.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /employees/1
# PATCH/PUT /employees/1.json
def update
respond_to do |format|
if #employee.update(employee_params)
format.html { redirect_to employees_url, notice: "#{#employee.first_name} was successfully updated."}
format.json { render :index, status: :ok, location: #employee }
else
format.html { render :edit }
format.json { render json: #employee.errors, status: :unprocessable_entity }
end
end
end
# DELETE /employees/1
# DELETE /employees/1.json
def destroy
#employee.destroy
respond_to do |format|
format.html { redirect_to employees_url, notice: 'Employee was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_employee
#employee = Employee.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def employee_params
if params[:employee][:password].blank? && params[:employee][:password_confirmation].blank?
params[:employee].delete(:password)
params[:employee].delete(:password_confirmation)
end
params[:employee].permit(:email, :password, :employee_id,:employee_work_id, :first_name, :middle_name, :last_name, :gender, :date_of_birth, :driver_license_no, :driver_license_expiry_date, :martial_status, :nationality, :office_address, :residence_address, :city, :state_province, :zip_code, :country, :work_number, :mobile_number, :home_number, :other_email)
end
end
app/controllers/insurance_controller.rb:
class InsurancesController < ApplicationController
before_action :set_insurance, only: [:show, :edit, :update, :destroy]
respond_to :html
def index
#insurances = Insurance.all
respond_with(#insurances)
end
def show
respond_with(#insurance)
end
def new
#insurance = Insurance.new
respond_with(#insurance)
end
def edit
end
def create
#insurance = Insurance.new(insurance_params)
#insurance.save
respond_with(#insurance)
end
def update
#insurance.update(insurance_params)
respond_with(#insurance)
end
def destroy
#insurance.destroy
respond_with(#insurance)
end
private
def set_insurance
#insurance = Insurance.find(params[:id])
end
def insurance_params
params.require(:insurance).permit(:employee_id,:name_of_dependent, :relationship, :name, :of_spouse, :children, :date_of_birth, :policy_number, :policy_provider, :policy_type)
end
end
app/views/insurances/_show.html.erb:
<%= employee.insurances.each do |emp| %>
<p>
<strong>Name of dependent:</strong>
<%= emp.name_of_dependent %>
</p>
<p>
<strong>Name:</strong>
<%= emp.name %>
</p>
<% end %>
When i use link_to with show path, it is working fine.
app/views/employees/show.html.haml:
%p
%strong Title:
= #employee.full_name
%p
%strong Text:
= #employee.gender
%p
= link_to 'Insurance', insurance_path
after accordion code, i used render as follows:
%p
%strong Title:
= #employee.full_name
%p
%strong Text:
= #employee.gender
%p
#accordion2.panel-group
#new-student-widget.panel.panel-default.left-column-entry
.header.panel-heading
.header-content.panel-title
%a#newStudentToggle{"data-parent" => "#accordion2", "data-target" => "#newStudent", "data-toggle" => "collapse"} Insurance Details
#newStudent.panel-collapse.collapse
#newStudentInner.panel-body
= render :template => 'insurances/show', locals: { employee: #employee }
When i am using render in accordion, i am getting error as:
NoMethodError in Employees#show
undefined method `name_of_dependent' for nil:NilClass
Please help me out.
If you are calling show as partial then rename show.html to _show.html
and pass #employeee instance variable which is present in accordion code
= render :template => 'insurances/show', locals: { employee: #employee }
and in _show page
- employee.insurances.each do |ins|
%p.strong Name of dependent:
= ins.name_of_dependent
%p.strong Name:
= ins.name
Pass the insurance object when you are rendering the template :
- #insurances.each do |insurancce|
= render template: 'insurances/show', locals: { insurance: insurance }
- end
Make sure you instantiated the #insurance object in your controller action, where you instantiated the #employee object.
#employee = current_user # or anything else
#insurances = #employee.insurances
Then in your Insurances#show template use insurance instead of #insurance like this :
<p id="notice"><%= notice %></p>
<p>
<strong>Name of dependent:</strong>
<%= insurance.name_of_dependent %>
</p>
<p>
<strong>Name:</strong>
<%= insurance.name %>
</p>

NoMethodError in Clients#new

So I'm getting this error in one of my views and it seems to have to do with the way client is being initialized in the controller, here's the code for my Client model and controller:
Model:
class Client < ActiveRecord::Base
has_many :visits
has_many :exchanges, through: :visits
Controller:
class ClientsController < ApplicationController
before_action :set_client, only: [:show, :edit, :update, :destroy]
def index
#clients = Client.all
end
# GET /clients/new
def new
#client = Client.new
end
# POST /clients
# POST /clients.json
def create
#client = Client.new(client_params)
respond_to do |format|
if #client.save
format.html { redirect_to #client, notice: 'Client was successfully created.' }
format.json { render action: 'show', status: :created, location: #client }
else
format.html { render action: 'new' }
format.json { render json: #client.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /clients/1
# PATCH/PUT /clients/1.json
def update
respond_to do |format|
if #client.update(client_params)
format.html { redirect_to #client, notice: 'Client was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #client.errors, status: :unprocessable_entity }
end
end
end
# DELETE /clients/1
# DELETE /clients/1.json
def destroy
#client.destroy
respond_to do |format|
format.html { redirect_to clients_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_client
#client = Client.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def client_params
#hidden for security
end
end
So the error goes off at line 1 for my client form when it calls #client and says "undefined method `model_name' for ActiveRecord::Relation::ActiveRecord_Relation_Client:Class" Really could use some help as I have no idea what is going on, thanks.
Error Stack:
Started GET "/clients/new" for 127.0.0.1 at 2014-04-06 14:05:48 -0400
Processing by ClientsController#new as HTML
Rendered clients/_form.html.erb (62.2ms)
Rendered clients/new.html.erb within layouts/application (65.3ms)
Completed 500 Internal Server Error in 68ms
ActionView::Template::Error (undefined method `model_name' for ActiveRecord::Relation::ActiveRecord_Relation_Client:Class):
1: <%= simple_form_for(#client) do |f| %>
2: <% if #client.errors.any? %>
3: <div id="error_explanation">
4: <h2><%= pluralize(#client.errors.count, "error") %> prohibited this client from being saved:</h2>
app/views/clients/_form.html.erb:1:in `_app_views_clients__form_html_erb___2200324505640086965_70348410359440'
app/views/clients/new.html.erb:3:in `_app_views_clients_new_html_erb___3059029162300151807_70348376263300'
Rendered /Library/Ruby/Gems/2.0.0/gems/actionpack-4.0.4/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.6ms)
Rendered /Library/Ruby/Gems/2.0.0/gems/actionpack-4.0.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (0.8ms)
Rendered /Library/Ruby/Gems/2.0.0/gems/actionpack-4.0.4/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (12.8ms)

Resources