nil when trying to display data in rails app - ruby-on-rails

I get this error when trying to show <%= #schedule.title %>, but when I do the same with <%= #lesson.title %> it is working fine for #lesson.
![undefined method `title' for nil:NilClass
]1
The flow is like this.
- A user signs up and creates a clinic, the clinic belongs to the user.
- A clinic has many practitioners and they belongs to the clinic.
- A practitioner has many lessons and schedules, and they belongs to the practitioner.
When I'm on the lesson show page, there is a link to a booking page. It's on this booking page that the error occours.
I know it's saying nil, but both lessons and schedules have been created for that specific practitioner.
Anybody knows why this is happening? I don't understand why I can access #lesson but not #schedule. Any help would be much appreciated.
routes.rb
resources :clinics do
resources :practitioners do
resources :lessons, :lesson_payments, :schedules do
resources :bookings do
end
end
end
end
schedules_controller.rb
class SchedulesController < ApplicationController
before_action :set_schedule, only: [:show, :edit, :update, :destroy]
# GET /schedules
# GET /schedules.json
def index
#schedules = Schedule.all
end
# GET /schedules/1
# GET /schedules/1.json
def show
end
# GET /schedules/new
def new
#schedule = Schedule.new
end
# GET /schedules/1/edit
def edit
end
# POST /schedules
# POST /schedules.json
def create
#schedule = Schedule.new(schedule_params)
respond_to do |format|
if #schedule.save
format.html { redirect_to clinic_practitioner_schedule_path(id: #schedule.id), notice: 'Schedule was successfully created.' }
format.json { render :show, status: :created, location: #schedule }
else
format.html { render :new }
format.json { render json: #schedule.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /schedules/1
# PATCH/PUT /schedules/1.json
def update
respond_to do |format|
if #schedule.update(schedule_params)
format.html { redirect_to clinic_practitioner_schedule_path(#schedule), notice: 'Schedule was successfully updated.' }
format.json { render :show, status: :ok, location: #schedule }
else
format.html { render :edit }
format.json { render json: #schedule.errors, status: :unprocessable_entity }
end
end
end
# DELETE /schedules/1
# DELETE /schedules/1.json
def destroy
#schedule.destroy
respond_to do |format|
format.html { redirect_to clinic_practitioner_schedules_url, notice: 'Schedule was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_schedule
#schedule = Schedule.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def schedule_params
params.require(:schedule).permit(:title, :start, :end, :practitioner_id, :account_id)
end
end
bookings_controller.rb
class BookingsController < ApplicationController
before_action :set_lesson, only: [:new]
def new
#account = Account.new
#user = User.new
#patient = Patient.new
#booking = Booking.new
#lesson_payment = LessonPayment.new
#schedule = Schedule.find_by_id(params[:id])
end
def create
create_patient_charge
create_patient_account
#user = User.new(user_params)
#user.account_id = #account.id
respond_to do |format|
if #user.save
create_patient_profile
create_patient_booking
create_patient_lesson_payment
auto_login(#user)
UserMailer.new_signup_booking_admin(#user, #booking).deliver_later
UserMailer.new_signup_booking_client(#user, #booking).deliver_later
format.html { redirect_to dashboard_url, notice: 'Your account was successfully created.' }
format.json { render :show, status: :created, location: #user }
else
format.html { redirect_back fallback_location: root_path, alert: 'An error occurred while sending this request.' }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
private
def set_lesson
#lesson = Lesson.find(params[:lesson_id])
end
def user_params
params.require(:user).permit(:email, :password, :time_zone)
end
def create_patient_account
#account = Account.new()
#account.status = 'active'
#account.account = 'prefix-' + SecureRandom.hex(4)
#account.account_type = 'client'
#account.save
end
def create_patient_profile
#patient = Patient.new()
#patient.firstname = params[:user][:patient][:patient_first_name]
#patient.lastname = params[:user][:patient][:patient_last_name]
#patient.phone = params[:user][:patient][:patient_phone]
#patient.user_id = #user.id
#patient.account_id = #user.account_id
#patient.save
end
def create_patient_booking
#lesson = Lesson.find(params[:user][:booking][:lesson_id])
#booking = Booking.new()
#booking.lesson_id = params[:user][:booking][:lesson_id]
#booking.schedule_id = params[:user][:booking][:schedule_id]
#booking.patient_id = #patient.id
#booking.account_id = #user.account_id
#booking.title = #lesson.title
#booking.cost = #lesson.cost
#booking.status = 'Booked'
#booking.save
#schedule = Schedule.find(params[:user][:booking][:schedule_id])
#booking.practitioner_id = #schedule.practitioner_id
#booking.start = #schedule.start
#booking.refunded = 0
#booking.save
#schedule.title = 'Booked'
#schedule.save
end
def create_patient_lesson_payment
#lesson_payment = LessonPayment.new()
#lesson_payment.status = 'Paid'
#lesson_payment.date = Date.today
#lesson_payment.cost = #lesson.cost
#lesson_payment.service = #lesson.title
#lesson_payment.booking_id = #booking.id
#lesson_payment.account_id = #user.account_id
#lesson_payment.save
end
end
This is where I link to the booking page
show.html.erb
<p id="notice"><%= notice %></p>
<%= link_to new_clinic_practitioner_lesson_booking_path(:lesson_id => #lesson.id), class: "course-btn" do %><i class="fa fa-calendar-plus-o"></i> Book This Lesson<% end %>
<p>
<strong>Image:</strong>
<%= #lesson.image %>
</p>
<p>
<strong>Title:</strong>
<%= #lesson.title %>
</p>
<p>
<strong>Duration:</strong>
<%= #lesson.duration %>
</p>
<p>
<strong>Cost:</strong>
<%= #lesson.cost %>
</p>
<p>
<strong>Category:</strong>
<%= #lesson.category %>
</p>
<p>
<strong>Language:</strong>
<%= #lesson.language %>
</p>
<p>
<strong>Level:</strong>
<%= #lesson.level %>
</p>
<p>
<strong>Description:</strong>
<%= #lesson.description %>
</p>
<p>
<strong>Practitioner:</strong>
<%= #lesson.practitioner_id %>
</p>
<p>
<strong>Account:</strong>
<%= #lesson.account_id %>
</p>
<%= link_to 'Edit', edit_clinic_practitioner_lesson_path(#lesson) %> |
<%= link_to 'Back', clinic_practitioner_lessons_path %>
new.html.erb
<h1>New Booking</h1>
<%= render 'form', booking: #booking %>
<%= link_to 'Back', clinic_practitioner_lesson_bookings_path %>
_form.html.erb
<table class="table table-bordered">
<thead>
<tr>
<th>Slots In The User's Time Zone</th>
<th>Price</th>
<th>Service Provider</th>
<th>Booking Button</th>
</tr>
</thead>
<tbody>
<tr>
<td><%= #lesson.title %></td>
<td><%= #schedule.title %></td>
</tr>
</tbody>
</table>

I am noticing that in you are initializing #schedule like this in your bookings_controller new method:
#schedule = Schedule.find_by_id(params[:id])
But, you don't have any params[:id] in your parameters that are:
{'clinic_id'=>'50','practitioner_id'=>'27','lesson_id'=>'15'}
This is why your #schedule is nil
Assuming, there is a has_many association between practitioner and schedule, and you want to display the title of first schedule of the practitioner, you can do it it like this:
#schedule = Schedule.find_by_practitioner_id(params[:practitioner_id])

Related

can't save to database with hidden field

I have 2 models, one of patients and another of indicadions, I think I have the relationships between the models correctly placed, what I cannot make it work is that the patient_id is placed in the hidden field
my models:
patient: has_many :prescription, dependent: :destroy
indication: belongs_to :patient
my view:
<%= form_with(model: prescription) do |form| %>
<% if prescription.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(prescription.errors.count, "error") %> prohibited this prescription from being saved:</h2>
<ul>
<% prescription.errors.each do |error| %>
<li><%= error.full_message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= form.hidden_field :patient_id, value: "patient_id" %>
<div class="form-group">
<%= form.label :content %>
<%= form.text_area :content, class:'form-control' %>
</div>
<%= form.submit "SAVE",class:'btn save' %>
<% end %>
The controller:
class PrescriptionsController < ApplicationController
before_action :set_prescription, only: %i[ show edit update destroy ]
# GET /prescriptions or /prescriptions.json
def index
#prescriptions = Prescription.all
end
# GET /prescriptions/1 or /prescriptions/1.json
def show
end
# GET /prescriptions/new
def new
#prescription = Prescription.new
end
# GET /prescriptions/1/edit
def edit
end
# POST /prescriptions or /prescriptions.json
def create
#prescription = Prescription.new(prescription_params)
respond_to do |format|
if #prescription.save
format.html { redirect_to #prescription, notice: "La receta se creó con éxito." }
format.json { render :show, status: :created, location: #prescription }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #prescription.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /prescriptions/1 or /prescriptions/1.json
def update
respond_to do |format|
if #prescription.update(prescription_params)
format.html { redirect_to #prescription, notice: "Prescription was successfully updated." }
format.json { render :show, status: :ok, location: #prescription }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: #prescription.errors, status: :unprocessable_entity }
end
end
end
# DELETE /prescriptions/1 or /prescriptions/1.json
def destroy
#prescription.destroy
respond_to do |format|
format.html { redirect_to prescriptions_url, notice: "Prescription was successfully destroyed." }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_prescription
#prescription = Prescription.find(params[:id])
end
# Only allow a list of trusted parameters through.
def prescription_params
params.require(:prescription).permit(:content, :patient_id)
end
end
Instead of using a hidden input you might actually want to nest the routes to makes the relationship explicit instead of implicit:
resources :patients do
resources :perscriptions, shallow: true
end
class PrescriptionsController < ApplicationController
before_action :set_patient
before_action :set_prescription, only: %i[ show edit update destroy ]
# GET /patients/1/prescriptions or /patients/1/prescriptions.json
def index
#prescriptions = #patient.perscriptions
end
# GET /prescriptions/1 or /prescriptions/1.json
def show
end
# GET /patients/1/prescriptions/new
def new
#prescription = Prescription.new
end
# GET /prescriptions/1/edit
def edit
end
# POST /patients/1/prescriptions or /patients/1/prescriptions.json
def create
#prescription = #patient.perscriptions.new(prescription_params)
respond_to do |format|
if #prescription.save
format.html { redirect_to #prescription, notice: "La receta se creó con éxito." }
format.json { render :show, status: :created, location: #prescription }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #prescription.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /prescriptions/1 or /prescriptions/1.json
def update
respond_to do |format|
if #prescription.update(prescription_params)
format.html { redirect_to #prescription, notice: "Prescription was successfully updated." }
format.json { render :show, status: :ok, location: #prescription }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: #prescription.errors, status: :unprocessable_entity }
end
end
end
# DELETE /prescriptions/1 or /prescriptions/1.json
def destroy
#prescription.destroy
respond_to do |format|
format.html { redirect_to prescriptions_url, notice: "Prescription was successfully destroyed." }
format.json { head :no_content }
end
end
private
def set_patient
#patient = Patient.find(params[:patient_id])
end
def set_prescription
#prescription = Prescription.find(params[:id])
end
# Only allow a list of trusted parameters through.
def prescription_params
params.require(:prescription).permit(:content)
end
end
<%= form_with(model: [#patient, #perscription]) do |form| %>
<% if prescription.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(prescription.errors.count, "error") %> prohibited this prescription from being saved:</h2>
<ul>
<% prescription.errors.each do |error| %>
<li><%= error.full_message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-group">
<%= form.label :content %>
<%= form.text_area :content, class:'form-control' %>
</div>
<%= form.submit "SAVE", class:'btn save' %>
<% end %>

How to show nested database

Hello I have a nested database "processing" which belongst to "shopping_process". However I want somehow to see the messages, which are saved in processing. How can I do that? If I go to http://localhost:3000/processings/index the Error: Couldn't find Processing with 'id'=index appears. Has somebody an idea?
processings_controller.rb
class ProcessingsController < ApplicationController
before_action :set_processing, only: [:show, :edit, :update, :destroy]
# GET /processings
# GET /processings.json
def index
#processings = Processing.all
end
# GET /processings/1
# GET /processings/1.json
def show
end
# GET /processings/new
def new
#processing = Processing.new
end
# GET /processings/1/edit
def edit
end
# POST /processings
# POST /processings.json
def create
#processing = Processing.new(processing_params)
respond_to do |format|
if #processing.save
format.html { redirect_to #processing, notice: 'Processing was successfully created.' }
format.json { render :show, status: :created, location: #processing }
else
format.html { render :new }
format.json { render json: #processing.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /processings/1
# PATCH/PUT /processings/1.json
def update
respond_to do |format|
if #processing.update(processing_params)
format.html { redirect_to #processing, notice: 'Processing was successfully updated.' }
format.json { render :show, status: :ok, location: #processing }
else
format.html { render :edit }
format.json { render json: #processing.errors, status: :unprocessable_entity }
end
end
end
# DELETE /processings/1
# DELETE /processings/1.json
def destroy
#processing.destroy
respond_to do |format|
format.html { redirect_to processings_url, notice: 'Processing was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_processing
#processing = Processing.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def processing_params
params.require(:processing).permit(:shopping_process_id, :shopping_list_id, :accepted, :responded, :message)
end
end
view/processings/index.html.erb
<p id="notice"><%= notice %></p>
<h1>Processings</h1>
<table>
<thead>
<tr>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% #Processing.all.each do |processing| %>
<tr>
<td><%= link_to 'Show', processing %></td>
<td><%= link_to 'Edit', edit_processing_path(processing) %></td>
<td><%= link_to 'Destroy', processing, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Processing', new_processing_path %>
models/processing.rb
class Processing < ApplicationRecord
# db associations
belongs_to :shopping_process
belongs_to :shopping_list
# validations
validates :shopping_list, :presence => true
end
Now here comes the code for the database "shopping_processes"
shopping_processes_controller.rb
class ShoppingProcessesController < ApplicationController
load_and_authorize_resource
layout 'shopping_process', only: [:shopper_show, :senior_show]
# GET /shopping_processes/1
# GET /shopping_processes/1.json
def show
end
# POST /shopping_processes
# POST /shopping_processes.json
def create
#shopping_process.status =nil
#shopping_process.processed = nil
puts params.inspect
respond_to do |format|
if #shopping_process.save
format.html { redirect_to #shopping_process, notice: 'Shopping process was successfully created.' }
format.json { render :show, status: :created, location: #shopping_process }
else
format.html { render :new }
format.json { render json: #shopping_process.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /shopping_processes/1
# PATCH/PUT /shopping_processes/1.json
def update
respond_to do |format|
if #shopping_process.update(shopping_process_params)
format.html { redirect_to #shopping_process, notice: 'Shopping process was successfully updated.' }
format.json { render :show, status: :ok, location: #shopping_process }
else
format.html { render :edit }
format.json { render json: #shopping_process.errors, status: :unprocessable_entity }
end
end
end
# DELETE /shopping_processes/1
# DELETE /shopping_processes/1.json
def destroy
#shopping_process.destroy
respond_to do |format|
format.html { redirect_to shopping_processes_url, notice: 'Shopping process was successfully destroyed.' }
format.json { head :no_content }
end
end
def shopper_show
#shopping_process = ShoppingProcess.find(params[:id])
#users = {}
first = true
#shopping_process.shopping_lists.each do |shopping_list|
user = shopping_list.user
#users[user.id] = {color: (first ? 'blue' : 'yellow'), name: user.firstname + ' ' + user.lastname}
first = false
end
end
def senior_show
#shopping_process = ShoppingProcess.find(params[:id])
#shopping_process.shopping_lists.each do |shopping_list|
#if shopping_list.user == current_user
# #shopping_list = shopping_list
#end
#shopping_list = shopping_list
#to show the correct shopping list uncomment the block above and remove the declartion underneath it
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_shopping_process
#shopping_process = ShoppingProcess.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def shopping_process_params
params.require(:shopping_process).permit(:user_id, :status, :appointed, :processed, :shopping_list_id, processings_attributes: [ :shopping_list_id, :message ])
end
end
views/shopping_processes/form.html.erb
<%= form_for(shopping_process) do |f| %>
<% if shopping_process.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(shopping_process.errors.count, "error") %> prohibited this shopping_process from being saved:</h2>
<ul>
<% shopping_process.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :appointed %>
<%= f.datetime_select :appointed %>
</div>
<div class="field">
<%= f.label :shopper %>
<%= f.text_field :user_id, value: current_user.id, :readonly => true%>
</div>
<div class="field">
<%= f.label :shopping_list_id %>
<%= f.select :shopping_list_id, ShoppingList.accessible_by(current_ability).map{ |sl| [sl.name, sl.id] } %>
</div>
<!-- SUB FORM FOR NESTED RESOURCE : PROCESSINGS -->
<%= f.fields_for :processings, #shopping_process.processings.build do |ff| %>
<div>
<%= ff.label :Begleiter %>
<%= ff.select :shopping_list_id, ShoppingList.all.map{ |sl| [sl.user.firstname, sl.id]} , {:prompt => true} %>
</div>
<div>
<%= ff.label :message %>
<%= ff.text_field :message%>
</div>
<% end %>
<!-- Submit-->
<div class="actions">
<%= f.submit %>
</div>
<% end %>

CRUD db entity from other controller

I want to create, edit and delete db entity from other controller than generated by scaffold. I want to have validation, create and deletion without redirection. I don't want to use generated controller because i want to create at least 2 types of entities from one controller.
For now i have create without redirect but i don't have notification about entity creation.
This controller should support crud operations:
class SmartHomeController < ApplicationController
layout 'smart_home'
def index
#name = 'Home';
end
def settings
#name = 'Settings';
#place = Place.new;
#all_places = Place.all;
respond_to do |format|
if #place.save
format.html { redirect_to #place, :notice => 'A was successfully created.' }
else
# render new with validation errors
format.html { render :action => "settings" }
end
end
end
end
scaffold generated controller:
class PlacesController < ApplicationController
before_action :set_place, only: [:show, :edit, :update, :destroy]
# GET /places
# GET /places.json
def index
#places = Place.all
end
# GET /places/1
# GET /places/1.json
def show
end
# GET /places/new
def new
#place = Place.new
end
# GET /places/1/edit
def edit
end
# POST /places
# POST /places.json
def create
#place = Place.new(place_params)
respond_to do |format|
if #place.save
format.html { redirect_to smart_home_settings_path, notice: 'Place was successfully created.' }
format.json { render :show, status: :created, location: #place }
else
format.html { render :new }
format.json { render json: #place.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /places/1
# PATCH/PUT /places/1.json
def update
respond_to do |format|
if #place.update(place_params)
format.html { redirect_to #place, notice: 'Place was successfully updated.' }
format.json { render :show, status: :ok, location: #place }
else
format.html { render :edit }
format.json { render json: #place.errors, status: :unprocessable_entity }
end
end
end
# DELETE /places/1
# DELETE /places/1.json
def destroy
#place.destroy
respond_to do |format|
format.html { redirect_to places_url, notice: 'Place was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_place
#place = Place.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def place_params
params.require(:place).permit(:name, :hw)
end
end
Could you guide me how to achieve that?
Edit. New code.
Page:
<div class="demo-cards mdl-cell mdl-cell--4-col mdl-cell--8-col-tablet mdl-grid mdl-grid--no-spacing"
style="width: 420px">
<div class="demo-updates mdl-card mdl-shadow--2dp mdl-cell mdl-cell--4-col mdl-cell--4-col-tablet mdl-cell--12-col-desktop">
<div class="mdl-card__title mdl-card--expand mdl-color--teal-300">
<h2 class="mdl-card__title-text">All places</h2>
</div>
<div class="mdl-card__supporting-text mdl-color-text--grey-600">
<ul class="demo-list-item mdl-list">
<% #all_places.each do |place| %>
<li class="mdl-list__item">
<span class="mdl-list__item-primary-content">
<%= place.name %>: <%= place.hw %> <%= link_to 'Destroy', place, controller: 'smart_home', action: 'delete_place', data: { confirm: 'Are you sure?' } %>
</span>
</li>
<% end %>
</ul>
</div>
</div>
</div>
<div class="demo-cards mdl-cell mdl-cell--4-col mdl-cell--8-col-tablet mdl-grid mdl-grid--no-spacing"
style="width: 420px">
<div class="demo-updates mdl-card mdl-shadow--2dp mdl-cell mdl-cell--4-col mdl-cell--4-col-tablet mdl-cell--12-col-desktop">
<div class="mdl-card__title mdl-card--expand mdl-color--teal-300">
<h2 class="mdl-card__title-text">Create place</h2>
</div>
<div class="mdl-card__supporting-text mdl-color-text--grey-600">
<table class="mdl-data-table mdl-js-data-table mdl-data-table--selectable mdl-shadow--2dp create-place-table">
<%= form_for #place, url: smart_home_create_path do |f| %>
<tr>
<td>
<div class="mdl-textfield mdl-js-textfield">
<%= f.label :name, 'Name', class: 'mdl-textfield__label' %>
<%= f.text_field :name, class: 'mdl-textfield__input' %>
</div>
</td>
</tr>
<tr>
<td>
<div class="mdl-textfield mdl-js-textfield">
<%= f.label :hw, class: 'mdl-textfield__label' %>
<%= f.text_field :hw, class: 'mdl-textfield__input' %>
</div>
</td>
</tr>
<tr>
<td>
<%= f.submit "Create", class: 'mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect' %>
</td>
</tr>
<% end %>
</table>
</div>
</div>
</div>
Controller:
class PlacesController < ApplicationController
before_action :set_place, only: [:show, :edit, :update, :destroy]
# GET /places
# GET /places.json
def index
#places = Place.all
end
# GET /places/1
# GET /places/1.json
def show
end
# GET /places/new
def new
#place = Place.new
end
# GET /places/1/edit
def edit
end
# POST /places
# POST /places.json
def create
#place = Place.new(place_params)
respond_to do |format|
if #place.save
format.html { redirect_to smart_home_settings_path, notice: 'Place was successfully created.' }
format.json { render :show, status: :created, location: #place }
else
format.html { render :new }
format.json { render json: #place.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /places/1
# PATCH/PUT /places/1.json
def update
respond_to do |format|
if #place.update(place_params)
format.html { redirect_to #place, notice: 'Place was successfully updated.' }
format.json { render :show, status: :ok, location: #place }
else
format.html { render :edit }
format.json { render json: #place.errors, status: :unprocessable_entity }
end
end
end
# DELETE /places/1
# DELETE /places/1.json
def destroy
#place.destroy
respond_to do |format|
format.html { redirect_to smart_home_settings_path, notice: 'Place was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_place
#place = Place.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def place_params
params.require(:place).permit(:name, :hw)
end
end
Deletion works but no confirm:
Page:
<%= link_to 'Destroy', delete_place_path(id: place.id), data: {:confirm => 'Are you sure?'}, :method => :delete %>
Controller:
def delete_place
place = Place.find(params[:id])
place.destroy
respond_to do |format|
format.html { redirect_to smart_home_settings_path, notice: 'Place was successfully destroyed.' }
format.json { head :no_content }
end
end
Routes:
get 'delete_place/:id' => 'smart_home#delete_place', as: :delete_place
Edit:
Javascript include was missed
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>

find_or_create_by_name not working when trying to associate tasks with lists on todolist app

Rails newbie working on associating tasks with lists and running into trouble when I try and interact with forms after I start the rails server.
Here's the error I'm getting. Any ideas?
Thanks!
NoMethodError in TasksController#create
undefined method `find_or_create_by_name' for #<Class:0x00000102a8bad0>
Rails.root: /Users/user/rails_projects/todolist
Application Trace | Framework Trace | Full Trace
app/models/task.rb:15:in `list_name='
app/controllers/tasks_controller.rb:43:in `new'
app/controllers/tasks_controller.rb:43:in `create'
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"B7g7u+v5USPRhefdFPt84xGkKjB1nVwy62IJj6SHJpc=",
"task"=>{"description"=>"Milk",
"list_name"=>"Shopping"},
"commit"=>"Create Task"}
ListsController:
class ListsController < ApplicationController
# GET /lists
# GET /lists.json
def index
#lists = List.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #lists }
end
end
# GET /lists/1
# GET /lists/1.json
def show
#list = List.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #list }
end
end
# GET /lists/new
# GET /lists/new.json
def new
#list = List.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #list }
end
end
# GET /lists/1/edit
def edit
#list = List.find(params[:id])
end
# POST /lists
# POST /lists.json
def create
#list = List.new(params[:list])
respond_to do |format|
if #list.save
format.html { redirect_to #list, notice: 'List was successfully created.' }
format.json { render json: #list, status: :created, location: #list }
else
format.html { render action: "new" }
format.json { render json: #list.errors, status: :unprocessable_entity }
end
end
end
# PUT /lists/1
# PUT /lists/1.json
def update
#list = List.find(params[:id])
respond_to do |format|
if #list.update_attributes(params[:list])
format.html { redirect_to #list, notice: 'List was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #list.errors, status: :unprocessable_entity }
end
end
end
# DELETE /lists/1
# DELETE /lists/1.json
def destroy
#list = List.find(params[:id])
#list.destroy
respond_to do |format|
format.html { redirect_to lists_url }
format.json { head :no_content }
end
end
end
TasksController:
class TasksController < ApplicationController
# GET /tasks
# GET /tasks.json
def index
#tasks = Task.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #tasks }
end
end
# GET /tasks/1
# GET /tasks/1.json
def show
#task = Task.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #task }
end
end
# GET /tasks/new
# GET /tasks/new.json
def new
#task = Task.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #task }
end
end
# GET /tasks/1/edit
def edit
#task = Task.find(params[:id])
end
# POST /tasks
# POST /tasks.json
def create
#task = Task.new(params[:task])
respond_to do |format|
if #task.save
format.html { redirect_to #task, notice: 'Task was successfully created.' }
format.json { render json: #task, status: :created, location: #task }
else
format.html { render action: "new" }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
# PUT /tasks/1
# PUT /tasks/1.json
def update
#task = Task.find(params[:id])
respond_to do |format|
if #task.update_attributes(params[:task])
format.html { redirect_to #task, notice: 'Task was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
# DELETE /tasks/1
# DELETE /tasks/1.json
def destroy
#task = Task.find(params[:id])
#task.destroy
respond_to do |format|
format.html { redirect_to tasks_url }
format.json { head :no_content }
end
end
end
Task model:
class Task < ActiveRecord::Base
attr_accessible :description, :list_name
belongs_to :list, :foreign_key => "list_id"
def name
#list = List.find(params[:id])
end
def list_name
list.name if self.list
end
def list_name=(str)
self.list = List.find_or_create_by_name(str)
end
end
List model:
class List < ActiveRecord::Base
attr_accessible :title
has_many :tasks
def name
#list = List.find(params[:id])
end
end
Partial for Tasks:
<%= form_for(#task) do |f| %>
<% if #task.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#task.errors.count, "error") %> prohibited this task from being saved:</h2>
<ul>
<% #task.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :description %><br />
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.label :list_name %><br />
<%= f.text_field :list_name %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Partial for Lists:
<%= form_for(#list) do |f| %>
<% if #list.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#list.errors.count, "error") %> prohibited this list from being saved:</h2>
<ul>
<% #list.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
The dynamic finders find_or_create_by_*... have been deprecated in Rails 4, as can be read about here.
However find_or_create_by is still supported.
In other words, instead of
find_or_create_by_name( 'Alice' ) # DEPRECATED
do
find_or_create_by( name: 'Alice' ) # OK
Rails' dynamic finders (find_by_... and find_or_create_by_...) are generated using the attributes of a model. You were using find_or_create_by_name when name wasn't an attribute on the List model.
Changing that to find_or_create_by_title(...) fixes the problem.

Rails Displaying a category name from a belongs_to

I would like to display a category name instead of a number (cat_id) from a belongs to relationship, I have cars and makes, basically here's the code -
show.html.erb
<p id="notice"><%= notice %></p>
<p>
<b>Make:</b>
<%= #car.make_id %>
</p>
<h2>
<em><%= #car.model %> <%= #car.body_typw %> <%= #car.engine_size %> <%= #car.trim %></em>
</h2>
<p>
<%= image_tag #car.image(:large) %>
</p>
<% #carimages.each do |carimage| %>
<%= image_tag carimage.image(:thumb), :class => "imgsmall" %>
<% end %>
<p>
<b>Transmission:</b>
<%= #car.transmission %>
</p>
<p>
<b>Fuel type:</b>
<%= #car.fuel_type %>
</p>
<p>
<b>Millage:</b>
<%= #car.millage %>
</p>
<p>
<b>Price:</b>
<%= number_to_currency(#car.price) %>
</p>
<p>
<%= raw #car.content %>
</p>
So basically i want the Make name here:-
<p>
<b>Make:</b>
<%= #car.make_id %>
</p>
cars_controller.rb
class CarsController < ApplicationController
# GET /cars
# GET /cars.json
def index
#cars = Car.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #cars }
end
end
# GET /cars/1
# GET /cars/1.json
def show
#car = Car.find(params[:id])
#pages = Page.all
#carimages = Carimage.all
#carimages = Carimage.find(:all, :limit => 10, :order => "id DESC")
respond_to do |format|
format.html # show.html.erb
format.json { render json: #car }
end
end
# GET /cars/new
# GET /cars/new.json
def new
#car = Car.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #car }
end
end
# GET /cars/1/edit
def edit
#car = Car.find(params[:id])
end
# POST /cars
# POST /cars.json
def create
#car = Car.new(params[:car])
respond_to do |format|
if #car.save
format.html { redirect_to #car, notice: 'Car was successfully created.' }
format.json { render json: #car, status: :created, location: #car }
else
format.html { render action: "new" }
format.json { render json: #car.errors, status: :unprocessable_entity }
end
end
end
# PUT /cars/1
# PUT /cars/1.json
def update
#car = Car.find(params[:id])
respond_to do |format|
if #car.update_attributes(params[:car])
format.html { redirect_to #car, notice: 'Car was successfully updated.' }
format.json { head :ok }
else
format.html { render action: "edit" }
format.json { render json: #car.errors, status: :unprocessable_entity }
end
end
end
# DELETE /cars/1
# DELETE /cars/1.json
def destroy
#car = Car.find(params[:id])
#car.destroy
respond_to do |format|
format.html { redirect_to cars_url }
format.json { head :ok }
end
end
end
it is related through make table - id and car table - make_id
Thanks
Robbie
Sure - the belongs to relationship gives you an object (a Make in your case), which you can call methods on - including getting field names!
So, If you set up your models like so:
class Car < ActiveRecord::Base
belongs_to :make
end
class Make < ActiveRecord::Base
end
And Make has a field named name, you could in your view:
<p>
<b>Make:</b>
<%= #car.make.name %>
</p>

Resources