Namespace and Simple_Form Hitting The Right Controller/Action - ruby-on-rails

I have a form on a cart page to update line_items. So the resource I am updating needs to exit the cart controller and enter the line_items controller... I am using the following form...
<%= simple_form_for shifted_commerce_line_item_path(item),
:url => {controller: 'line_items', action: 'update'} do |f| %>
I get no route matches...
No route matches {:action=>"update", :controller=>"shifted_commerce/line_items"}
The thing is... I have the the action in the controller...
I'll post my routes.
shifted_commerce_line_items GET /shifted_commerce/line_items(.:format) shifted_commerce/line_items#index
POST /shifted_commerce/line_items(.:format) shifted_commerce/line_items#create
new_shifted_commerce_line_item GET /shifted_commerce/line_items/new(.:format) shifted_commerce/line_items#new
edit_shifted_commerce_line_item GET /shifted_commerce/line_items/:id/edit(.:format) shifted_commerce/line_items#edit
shifted_commerce_line_item GET /shifted_commerce/line_items/:id(.:format) shifted_commerce/line_items#show
PATCH /shifted_commerce/line_items/:id(.:format) shifted_commerce/line_items#update
PUT /shifted_commerce/line_items/:id(.:format) shifted_commerce/line_items#update
DELETE /shifted_commerce/line_items/:id(.:format) shifted_commerce/line_items#destroy
How do I get this form to hit the update action in my controller?
Don't we see the above route? both PUT and PATCH match /shifted_commerce/Line_items/:id...and I'm passing the id with the (item)...
Update 1 I'll also add that I'm running this form in a loop, so every line_item can be edited. #anything isn't what I'd want to pass to the path for an ID... also, I'm operating from the carts controller, in the show action. Not a line_item controller, edit action.
Update 2 If I do the following simple_form_for:
<%= simple_form_for shifted_commerce_line_item_path(item), :url => {controller: 'line_items', action: 'create'} do |f| %>
It successfully takes me into the create action of the line_items controller. But if I do
<%= simple_form_for shifted_commerce_line_item_path(item), :url => {controller: 'line_items', action: 'update'} do |f| %>
I get the route error. What's the deal?! Why does it work for create but not for update? I have the update action in my controller...
ShiftedCommerce::LineItemsController
class ShiftedCommerce::LineItemsController < ApplicationController
before_action :set_line_item, only: [:show, :edit, :update, :destroy]
before_action :set_line_item_item, only: [:show, :edit, :update, :destroy]
# GET /line_items
# GET /line_items.json
def index
#line_items = ShiftedCommerce::LineItem.all
end
# GET /line_items/1
# GET /line_items/1.json
def show
end
# GET /line_items/new
def new
#line_item = ShiftedCommerce::LineItem.new
end
# GET /line_items/1/edit
def edit
end
# POST /line_items
# POST /line_items.json
def create
#cart = current_cart
# item is built from base_item, after finding associated product
#base_item_id = params[:shifted_commerce_line_item][:base_item_id]
get_item_id_from_base_item_params
build_line_item
## Does a line item with the same itemt_id already exist in cart?
if #line_item.exists_in_collect?(current_cart.line_items)
#if so, change quantity, check if there's enough stock
if current_cart.where_line_item_with(#item_id).update_quantity(#line_item.quantity) == true
#line_item.destroy
redirect_to shifted_commerce_base_items_path
flash[:success] = "Detected item In Cart, Added Your Amount More to Quantity"
else #otherwise there's not enough product in stock.
redirect_to shifted_commerce_cart_path
flash[:failure] = "Cannot Add To Cart, Not Enough In Stock"
end
else # This product isn't in the cart already let's save it!
if #line_item.have_enough_item? == true # if there is enough stock, save
if #line_item.save
respond_to do |format|
format.html { redirect_to shifted_commerce_base_items_path,
:notice => "Added to Cart." }
format.xml { render :xml => #line_item,
:status => :created, :location => #line_item }
end
else
format.xml { render :xml => #line_item.errors,
:status => :unprocessable_entity }
end
else # not enough stock, not saved.
redirect_to shifted_commerce_base_items_path
if #line_item.item.stock_qty > 0
flash[:failure] = "Sorry! We Only Don't Have Enough In Stock"
else
flash[:failure] = "Sorry! That Item Is Out Stock"
end
end
end
end
# PATCH/PUT /line_items/1
# PATCH/PUT /line_items/1.json
def update
#line_item = ShiftedCommerce::LineItem.find(params[:id])
raise
#line_item.attributes = line_item_params
if #line_item.over_order_cap? #is the quantity over maximum?
flash[:error] = "Contact Us For Orders of This Size -- Quantity Set To Max"
redirect_to cart_path
else # quantity to change to not over maximum.
if #line_item.have_enough_item? == true
#line_item.update(line_item_params)
#did they update quantity to 0?
if #line_item.quantity <= 0
#line_item.destroy
flash[:success] = "Item Removed"
redirect_to :back
else
flash[:success] = "Itemed Updated"
redirect_to cart_path
end
else
redirect_to cart_path
flash[:failure] = "We Don't Have Enough In Stock. Update Failed"
end
end
end
# DELETE /line_items/1
# DELETE /line_items/1.json
def destroy
#line_item.destroy
respond_to do |format|
format.html { redirect_to line_items_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_line_item
#line_item = LineItem.find(params[:id])
end
def set_line_item_item
#line_item_name = #line_item.item.base_item
end
# Never trust parameters from the scary internet, only allow the white list through.
def line_item_params
params.fetch(:shifted_commerce_line_item, {}).permit(:item_id, :cart_id, :order_id, :quantity, :weight, :units)
end
def build_line_item
#line_item = #cart.line_items.build(
:item_id => #item_id,
:order_id => nil,
:weight => params[:shifted_commerce_line_item][:weight],
:quantity => params[:shifted_commerce_line_item][:quantity]
)
end
def get_item_id_from_base_item_params
#item_id = ShiftedCommerce::Item.where(:base_item_id => #base_item_id).where(:size_id => params[:shifted_commerce_line_item][:size]).first.id
end
end
line_item.rb
class ShiftedCommerce::LineItem < ActiveRecord::Base
belongs_to :item
belongs_to :cart
after_create :set_order_weight#, :set_package_dimentions
after_update :set_order_weight#, :set_package_dimentions
#max capactiy here
def have_enough_item?
if self.item.stock_qty >= self.quantity
return true
else
if self.quantity_was == nil
return false
else
self.quantity = self.quantity_was
self.save
return false
end
end
end
def set_order_weight
if
self.cart.nil?
else
self.cart.total_weight = self.cart.line_items.to_a.sum {|item| (item.weight)*(item.quantity)}
self.cart.save
end
end
def over_order_cap?
if self.quantity > 5
self.quantity = 5
self.save
return true
end
return false
end
def update_quantity(qty)
self.quantity += qty
if self.have_enough_item? == true
self.save
end
end
def exists_in_collect?(items)
items.each do |item|
return true if self.item_id == item.item_id
end
return false
end
def set_order_total_units
if
self.cart.nil?
else
self.set_cart_units
self.cart.total_units = self.cart.total_units
self.cart.save
end
end
def total_price
item.base_item.price * quantity
end
end
Routes.rb
namespace :shifted_commerce do
resources :line_items
resources :items
resources :base_items
resource :cart, only: [:show, :update, :destroy] do
resource :order, only: [:show, :create, :update, :edit, :new]
end
end

Change this and try:
<%= simple_form_for item, url: shifted_commerce_line_items_path(item), method: :put do |f| %>
as per you routes
Update:
Sorry it must be post but not put like this:
<%= simple_form_for item, url: shifted_commerce_line_item_path(item), method: :post do |f| %>

Try using <%= simple_form_for ([:shifted_commerce, item]) do |f| %> or
<%= simple_form_for item, :url => shifted_commerce_line_item_path do |f| %>

Related

How to create an object when update another with nested_form (has_many belongs_to association)

I have two models, Clients and Calls, with a has_many - belongs_to association. I want to create a new call every time a update the client. Using the nested_form, I was able to create it, but it's generating an empty object, with no params.
Models.rb
class Call < ActiveRecord::Base
belongs_to :client
has_and_belongs_to_many :interests
end
class Client < ActiveRecord::Base
has_many :calls, :dependent => :destroy
belongs_to :user
has_and_belongs_to_many :interests
accepts_nested_attributes_for :calls
end
calls_controller.rb
class Admin::CallsController < ApplicationController
before_action :set_call, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
layout 'admin'
# GET /calls
def index
#calls = Call.order(created_at: :desc)
end
# GET /calls/1
def show
#calls = Call.order(created_at: :desc)
end
# GET /calls/new
def new
# #call = Call.new
end
# GET /calls/1/edit
def edit
end
# POST /calls
def create
#client = Client.find(params[:client_id])
#call = #client.calls.create(call_params)
if #call.save
redirect_to [:admin, #client], notice: 'Atendimento criado com sucesso.'
#call.create_activity :create, owner: current_user
else
render :new
end
end
# PATCH/PUT /calls/1
def update
# if #call.update(call_params)
# redirect_to #call, notice: 'Artigo editado com sucesso.'
# else
# render :edit
# end
end
# DELETE /calls/1
def destroy
#client = Client.find params[:client_id]
#call = #client.calls.find params[:id]
#call.destroy
redirect_to (:back), notice: 'Atendimento excluído.'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_call
#call = Call.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def call_params
params.require(:call).permit(:resume, :calltype, :client_id, interest_ids:[])
end
end
clients_controller.rb
class Admin::ClientsController < ApplicationController
before_action :set_client, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
layout 'admin'
# Clients.paginate(:page => params[:page], :per_page => 30)
# GET /clients
# GET /clients.json
def index
#user = current_user
#calls = Call.order(created_at: :desc)
if #user.admin?
#clients = Client.order(created_at: :desc).paginate(:page => params[:page], :per_page => 20)
#condition = 'ADMINISTRADOR'
#clients_count = Client.count
else
#clients = #user.clients.order(updated_at: :desc).paginate(:page => params[:page], :per_page => 20)
#condition = 'CORRETOR'
#clients_count = #user.clients.count
end
end
# GET /clients/1
# GET /clients/1.json
def show
#client = Client.find(params[:id])
# #calls = Call.order(created_at: :desc)
#user = current_user
#.....
end
# GET /clients/new
def new
#client = Client.new
end
# GET /clients/1/edit
def edit
end
# POST /clients
# POST /clients.json
def create
#client = Client.new(client_params)
if #client.save
redirect_to [:admin, #client], notice: 'Obrigado pelo Cadastro, entraremos em contato.'
ClientMailer.new_lead(#client).deliver!
else
render new_admin_client_path, notice: 'OOPS! Há problemas no seu formulário, verifique por favor.'
end
end
# PATCH/PUT /clients/1
# PATCH/PUT /clients/1.json
def update
if #client.update(client_params)
#client.calls.create(#client[:client_id])
redirect_to admin_clients_path(current_user), notice: 'Cliente atribuído ao corretor '
# ClientMailer.client_user_set(#client).deliver_now
else
render :edit
end
end
# DELETE /clients/1
# DELETE /clients/1.json
def destroy
#client.destroy
redirect_to admin_clients_url, notice: 'Cliente deletado'
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
params.require(:client).permit(:name, :telephone, :email, :message, :user_id, :origin, :rg, :cpf, :street, :number, :birthday, :attended, interest_ids:[])
end
end
clients/edit.slim
= simple_form_for ([:admin, #client]) do |f|
h4 = f.error_notification
.row
-if current_user.admin?
.input-field
= f.collection_select :user_id, User.all, :id, :name, { prompt: "Selecione o corretor..." }
h3.title Interesses do cliente
.input-field
= f.collection_check_boxes :interest_ids, Interest.all, :id, :name do |b|
.col.s6.m3.collection-check-box
= b.check_box
= b.label
.row
= f.simple_fields_for ([:admin, :client, Call.new]) do |c|
.input-field#inline
= c.input :calltype, collection: ['E-mail', 'Telefone', "WhatsApp"], as: :radio_buttons, label: ""
.input-field
= c.input :resume, label: 'Resumo do atendimento'
.row
= f.hidden_field :attended, value: true
.input-field.center
= f.button :submit, 'Salvar', class: 'btn-large'
Could you do something like this in the controller instead, placing inside the client update block.
#call = Call.new
#call.calltype = somevalue
#call.resume = someothervalue
#call.client_id = valueofclientid
#call.save
Looks like the values are resume, calltype, client_id, interest_ids? Would you have access to the values you want for those there?
I would make this a method below called something like make_new_call and then just call that, but it is up to you.
def make_new_call
// put the Call.new -> call.save code in here
end
Then in that method
if #client.update(client_params)
make_new_call
redirect_to admin_clients_path(current_user), notice: 'Cliente atribuído ao corretor '
# ClientMailer.client_user_set(#client).deliver_now
else
render :edit
end

Rails, after remote delete of item I get: First argument in form cannot contain nil or be empty

I want to delete an image on click.
This is in my view
<%=form_for #area, url: areas_update_path, remote: true, html: {class: "form-horizontal",:multipart => true} do |f|%>
....
<% #area.area_attachments.each do |a| %>
<%unless a.image.blank?%>
<%= link_to delete_area_attachment_path(a), :remote => true, :method => :delete do%>
<%= image_tag a.image_url(:thumb), class:"delete-image" %>
<% end %>
<% end %>
<% end %>
....
<% end %>
After I click on an image, the image gets deleted, but I get
First argument in form cannot contain nil or be empty
In the first line of the code that I posted (#area I guess)
My delete_area_attachment method in my area_attachments_controller
def delete_area_attachment
#areaAttachment = AreaAttachment.find(params[:id])
#areaAttachment.destroy
respond_to do |format|
format.js
end
end
I guess the #area variable has to be initialized, but why?
What I am trying to delete is an area_attachment not an area, and I already initialized it, so what does the #area variable has to do with that?
How do I go about it here?
EDIT:
my relative routes:
#Area Paths
get '/areas/new', to: 'areas#new', :as => 'areas_new'
post '/areas/create', to: 'areas#create', :as => 'areas_create'
get '/areas/:id/destroy', to: 'areas#destroy', :as => 'areas_destroy'
delete 'delete_area/:id', controller: 'areas', action: 'delete_area'
get '/areas/:id/edit', to: 'areas#edit', :as => 'areas_edit'
patch '/areas/:id/update', to: 'areas#update', :as => 'areas_update'
#Area Attachment Paths
delete 'delete_area_attachment/:id', controller: 'area_attachments', action: 'delete_area_attachment', :as => 'delete_area_attachment'
My areas_controller
class AreasController < ApplicationController
before_action :set_areas
before_action :set_area, only: [:edit, :delete, :update, :destroy]
def new
#area = Area.new
#languages = Language.all
#area_attachment = #area.area_attachments.build
end
def create
#area = Area.new(area_params)
if #area.save && manage_strings
params[:area_attachments]['image'].each do |a|
#area_attachment = #area.area_attachments.create!(:image => a, :area_id => #area.id)
end
#status = 'success'
else
#status = 'error'
#errormessages = #area.errors.full_messages
end
respond_to do |format|
format.js
end
end
def edit
end
def update
if #area.update(area_params) && manage_strings
params[:area_attachments]['image'].each do |a|
#area_attachment = #area.area_attachments.create!(:image => a, :area_id => #area.id)
end
#status = 'success'
else
#status = 'error'
#errormessages = #area.errors.full_messages
end
respond_to do |format|
format.js
end
end
def delete_area
#area = Area.find(params[:id])
#area.destroy
respond_to do |format|
format.js
end
end
def find_area_by_id
area = Area.find(params[:id])
render json: area
end
protected
def news_list
respond_to do |format|
format.js
end
end
private
def area_params
params.require(:area).permit(:id, area_attachments_attributes: [:id, :area_id, :image])
end
def set_area
#area = Area.find_by_id(params[:id])
#languages = Language.all
#area_attachments = #area.area_attachments.all
end
def set_areas
#areas = Area.all
end
def manage_strings
if params[:area][:strings].any?
params[:area][:strings].each do |key,value|
string = #area.article_localizations.find_or_initialize_by(:language_id => key.to_i)
string.title = params[:area][:strings][key][:title]
string.text = params[:area][:strings][key][:text]
string.save
end
end
end
end
In delete_area_attachment before #areaAttachment.destroy add:
#area = Area.find_by_id(#areaAttachment.area_id)

undefined method `model_name' for NilClass:Class when calling form in another controllers view

I have 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
#employee = Employee.find(params[:employee_id])
#insurance = #employee.insurances.create(insurance_params)
redirect_to employee_path(#employee)
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(: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:
- if #employee.insurances.exists?
- #employee.insurances.each do |emp|
%p
%strong Name of dependent:
= emp.name_of_dependent
%p
%strong Relationship:
= emp.relationship
%p
%strong Name of spouse:
= emp.name_of_spouse
%p
%strong Children:
= emp.children
%p
%strong Date of birth:
= emp.date_of_birth
%p
%strong Policy number:
= emp.policy_number
%p
%strong Policy provider:
= emp.policy_provider
%p
%strong Policy type:
= emp.policy_type
- else
= simple_form_for([:employee,#insurance]) do |f|
= f.error_notification
.form-inputs
= f.input :name_of_dependent
= f.input :relationship
= f.input :name_of_spouse
= f.input :children
= f.input :date_of_birth
= f.input :policy_number
= f.input :policy_provider
= f.input :policy_type
.form-actions
= f.button :submit
app/views/employees/show.html.haml:
%p
%strong Title:
= #employee.full_name
%p
%strong Text:
= #employee.gender
%p
%strong Insurance Details:
= render :partial => 'insurances/show', locals: { employee: #employee }
In the employees/show, when I render insurances/show, the show condition is working fine and when there are no records, the create form is not shown and it is listing error as:
undefined method `model_name' for NilClass:Class
I tried using = simple_form_for([:employee,Insurance.new], :url =>{:controller => "insurances", :action => :create) do |f| but it didn't fix my problem.
Use local variables inside of partials: employee instead of #employee.
When you render a partial and use locals: to pass in a variable, it is in fact passed in as a local variable. Instance variables of the same name will be nil.

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>

Ruby error with form

how to make route from appointment/new51 action to create51 action ? because it automatically redirect me to create and I don't want this. I am new in Ruby and I have lots of problems with my school project but it is almost finished:)
Routes.rb:
ZOZ::Application.routes.draw do
resources :refferals do
collection do
get 'new51'
end
member do
get 'show'
end
end
#17 potwierdzanie rejestracji
resources :appointments do
collection do
get 'search'
get 'search_result'
get 'to_confirm'
get 'new51'
end
member do
put :confirm
put :create51
end
end
resources :clinics do
collection do
get 'index51'
end
member do
get 'show51s'
end
end
resources :doctors do
collection do
get 'index51a'
get 'index51'
end
member do
get 'show51s'
get 'show51ss'
end
end
resources :patients do
collection do
get 'select51'
get 'index51'
end
member do
get 'show51s'
get 'show51ss'
end
end
get "welcome/index2"
get "welcome/index"
get 'appointments/create'
get 'appointments/move' => 'appointments#move'
post 'appointments/move' => 'appointments#doctors_list'
get 'appointments/move/:id' => 'appointments#doctor_appointments', as: :doctor_appointments
get 'appointments/change_appointment/:id' => 'appointments#change_appointment', as: :change_appointment
get 'appointments/change_doctor_and_appointment/:id' => 'appointments#change_doctor_and_appointment', as: :change_doctor_and_appointment
get 'appointments/success' => 'appointments#success'
# The priority is based upon order of creation:
# first created -> highest priority.
# Sample of regular route:
# match 'products/:id' => 'catalog#view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# Sample resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Sample resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Sample resource route with more complex sub-resources
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', :on => :collection
# end
# end
# Sample resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
root :to => 'welcome#index'
# See how all your routes lay out with "rake routes"
# This is a legacy wild controller route that's not recommended for RESTful applications.
# Note: This route will make all actions in every controller accessible via GET requests.
# match ':controller(/:action(/:id))(.:format)'
end
Appointments_controller:
class AppointmentsController < ApplicationController
before_filter :load_appointment, only: [:show, :update, :edit, :destroy]
before_filter :load_wizard, only: [:new, :edit, :create, :update]
def search
end
def new51
#doctors_workplace = DoctorsWorkplace.scoped
#doctors_workplace = #doctors_workplace.where(doctor_id: Doctor.find(session[:current_doctor_id2]).id)
#appointment = Appointment.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #appointment }
end
end
def create51
#appointment = Appointment.new(params[:appointment])
respond_to do |format|
if #appointment.save
format.html { redirect_to #appointment, notice: 'Appointment was successfully created.' }
format.json { render json: #appointment, status: :created, location: #appointment }
else
format.html do
#schedules = Schedule.scoped
#schedules = #schedules.where(doctor_id: Doctor.find(session[:current_doctor_id2]).id)
render action: "new51"
end
format.json { render json: #appointment.errors, status: :unprocessable_entity }
end
end
end
def search_result
d = params[:date]
data = Date.new(d["(1i)"].to_i, d["(2i)"].to_i, d["(3i)"].to_i)
#szukanie pacjenta
#patients = Patient.scoped
#patients = #patients.where(pesel: params[:pesel])
if params[:imie] != ""
#patients = #patients.where(imie: params[:imie])
end
if params[:nazwisko] != ""
#patients = #patients.where(nazwisko: params[:nazwisko])
end
#szukanie doctora
opcja = 0
#doctors = Doctor.scoped
if params[:imie_lekarza] != ""
#doctors = #doctors.where(imie_lekarza: params[:imie_lekarza])
opcja = 1
end
if params[:nazwisko_lekarza] != ""
#doctors = #doctors.where(nazwisko_lekarza: params[:nazwisko_lekarza])
opcja = 1
end
#zlaczenie
#patient_appo = #patients.first.appointments.where(:data_godzina_wizyty => data.beginning_of_day..data.end_of_day, potwierdzona: false)
if opcja == 1
#doctors_appo = #doctors.first.appointments.where(:data_godzina_wizyty => data.beginning_of_day..data.end_of_day, potwierdzona: false)
#appointments = #patient_appo & #doctors_appo
else
#appointments = #patient_appo
end
end
def to_confirm
session['last_search'] = request.env["HTTP_REFERER"]
#appointment = Appointment.find(params[:id])
#patient = Patient.find(#appointment.patient_id)
if #appointment.doctor_id != nil
#doctor = Doctor.find(#appointment.doctor_id)
end
if #appointment.refferal_id != nil
#refferal = Refferal.find(#appointment.refferal_id)
end
end
def confirm
#appointment = Appointment.find(params[:id])
#appointment.potwierdzona = true
if #appointment.save
#redirect_to :back, notice: 'Rejestracja zostala pomyslnie potwierdzona.'
redirect_to session[:last_search], notice: 'Rejestracja zostala pomyslnie potwierdzona.'
else
redirect_to :back, notice: 'Niestety wystapil blad. Prosze sprubowac pozniej'
end
end
def index
#appointments = Appointment.all
end
def show
end
def new
#appointment = #wizard.object
#clinics = Clinic.all
#doctors = Doctor.all
end
public
def findDoctorViaClinic( clinic )
return( (Clinic.find( clinic )).doctors.uniq )
end
helper_method :findDoctorViaClinic
def findScheduleViaDoctor(d)
s = Schedule.includes(:doctors_workplace).where(doctors_workplace_id: (DoctorsWorkplace.includes(:doctor).where(doctor_id: d)) ).where(taken: 0)
return s
end
helper_method :findScheduleViaDoctor
def edit
end
def create
#appointment = #wizard.object
if #wizard.save
s = ( Schedule.find( #appointment.schedule.id ) )
s.taken = true
s.save
redirect_to #appointment, notice: "Appointment saved!"
else
render :new
end
end
def update
if #wizard.save
redirect_to #appointment, notice: 'Appointment was successfully updated.'
else
render action: 'edit'
end
end
def destroy
#appointment.destroy
redirect_to appointments_url
end
private
def load_appointment
#appointment = Appointment.find(params[:id])
end
def load_wizard
#wizard = ModelWizard.new(#appointment || Appointment, session, params)
if self.action_name.in? %w[new edit]
#wizard.start
elsif self.action_name.in? %w[create update]
#wizard.process
end
end
end
_form51:
<%= form_for(#appointment) do |f| %>
<% if #appointment.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#appointment.errors.count, "error") %> prohibited this appointment from being saved:</h2>
<ul>
<% #appointment.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :data_godzina_wizyty %><br />
<%=
options = { start_year: 2.year.from_now.year,
end_year: 2013,
include_blank: true,
default: nil }
f.datetime_select :data_godzina_wizyty, options
%>
<!--<input type="text" data-behaviour='datepicker' :data_wizyty > -->
</div>
<div class="field">
<%= f.hidden_field :doctor_id, :value => Doctor.find(session[:current_doctor_id2]).id %>
</div>
<div class="field">
<%= f.hidden_field :patient_id, :value => Patient.find(session[:current_patient_id]).id %>
</div>
<div class="actions">
<%= submit_tag "Utworz wizyte" %>
</div>
<% end %>
wymaga_Potwierdzenia != wymaga_potwierdzenia
Correct to the right method/column name.

Resources