Ruby on rails form doesn't write into database - ruby-on-rails

I am suffering, because I don't get why my form doesn't write data into my database. If I submit the form I get a new line in the database, which only contains "id", "created at" and "updated at". All other parameters are not submitted. In the log file I get a "unpermitted parameters" message. Where can I change this?
I would be very happy for help. Thanks a lot!
Here is the view to the "new institute" page, which contains the form.
<% provide(:title, 'Institut erstellen') %>
<div class="small_jumbotron jumbotron">
<h1>Institut erstellen</h1>
<div class="row">
<div class="Links">
<%= form_for(#institute) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<br>
<%= f.label :Institutsname %>
<%= f.text_field :name, class: 'form-control' %>
<%= f.label :Professorenanzahl %>
<%= f.number_field :professors, class: 'form-control' %>
<%= f.label "Anzahl wissenschaftlicher Mitarbeiter" %>
<%= f.number_field :employees, class: 'form-control' %>
<%= f.label "Anzahl an Masterarbeiten" %>
<%= f.number_field :master_theses, class: 'form-control' %>
<%= f.label "Anzahl Lehrveranstaltungen" %>
<%= f.number_field :classes, class: 'form-control' %>
<%= f.label "Minimale Bachelorarbeitenzuordnung" %>
<%= f.number_field :min_workload, class: 'form-control' %>
<%= f.label "Überkapazitätsbereitschaft" %>
<%= f.number_field :overload, class: 'form-control' %>
<%= f.label "Aversion gegen Überkapazitäten" %>
<%= f.number_field :overload_aversion, class: 'form-control' %>
<%= f.label "Kapazität" %>
<%= f.number_field :capacity, class: 'form-control' %>
<br>
<%= f.submit "Erstelle das Institut", class: "btn btn-primary" %>
<% end %>
</div>
</div>
</div>
Here is the institutes controller
class InstitutesController < ApplicationController
before_action :set_institute, only: [:show, :edit, :update, :destroy]
# GET /institutes
# GET /institutes.json
def index
#institutes = Institute.all
end
# GET /institutes/1
# GET /institutes/1.json
def show
end
# GET /institutes/new
def new
#institute = Institute.new
end
# GET /institutes/1/edit
def edit
end
# POST /institutes
# POST /institutes.json
def create
#institute = Institute.new(institute_params)
respond_to do |format|
if #institute.save
format.html { redirect_to #institute, notice: 'Das Institut wurde erstellt.'}
format.json { render :show, status: :created, location: #institute }
else
format.html { render :new }
format.json { render json: #institute.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /institutes/1
# PATCH/PUT /institutes/1.json
def update
respond_to do |format|
if #institute.update(institute_params)
format.html { redirect_to #institute, notice: 'Die Institutsdaten wurden aktualisiert.' }
format.json { render :show, status: :ok, location: #institute }
else
format.html { render :edit }
format.json { render json: #institute.errors, status: :unprocessable_entity }
end
end
end
# DELETE /institutes/1
# DELETE /institutes/1.json
def destroy
#institute.destroy
respond_to do |format|
format.html { redirect_to institutes_url, notice: 'Das Institut wurde gelöscht.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_institute
#institute = Institute.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def institute_params
params.permit(:name, :professors, :employees, :master_theses, :classes, :min_workload, :overload, :overload_aversion, :capacity)
end
end
And now a snippet of the log file
Started POST "/institutes" for 127.0.0.1 at 2018-02-18 16:15:02 +0100
Processing by InstitutesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"ufyuHL2iXZpQg1ZmfG1pleuY7aL3JIl+eGn36UJeibML8U5R1sOgw8jd6geBB60XchttET2T3I1SndFgGsR2uA==", "institute"=>{"name"=>"wsd", "professors"=>"", "employees"=>"4", "master_theses"=>"", "classes"=>"", "min_workload"=>"", "overload"=>"", "overload_aversion"=>"", "capacity"=>""}, "commit"=>"Erstelle das Institut"}
Unpermitted parameters: :utf8, :authenticity_token, :institute, :commit
[1m[35m (0.5ms)[0m [1m[36mbegin transaction[0m
[1m[35mSQL (0.6ms)[0m [1m[32mINSERT INTO "institutes" ("created_at", "updated_at") VALUES (?, ?)[0m [["created_at", "2018-02-18 15:15:02.619018"], ["updated_at", "2018-02-18 15:15:02.619018"]]
[1m[35m (17.0ms)[0m [1m[36mcommit transaction[0m
Redirected to http://localhost:3000/institutes/12
Completed 302 Found in 30ms (ActiveRecord: 18.1ms)

You're not using strong_params correctly. Should be like this:
def institute_params
params.require(:institute).permit(:name, :professors, ...)
# ^^^^^^^^^^^^^^^^^^^^
end

Related

Edit form rendered blank

My model/id/edit form is rendered blank, without rendering the values that are already in the database. I don't see this is the regular behaviour in a brand new rails app.
Any insights what's blocking those values to be rendered in the form?
Rails 6.1.4
ruby 2.7.3p183
_form.html.erb
<%= form_with(model: task) do |form| %>
<%= render "shared/error_messages", resource: form.object %>
<div class="form-group">
<%= form.label :title %>
<%= form.text_field :title, class: "form-control", prepopulated: "true", :value => params[:title] %>
</div>
<div class="form-group">
<%= form.label :description %>
<%= form.rich_text_area :description, data: { controller: "mentions", mentions_target: "field" }, class: "form-control", :value => params[:description] %>
</div>
<div class="form-group">
<%= form.label :credits %>
<%= form.number_field :credits, class: "form-control", :value => params[:credits] %>
</div>
<div class="form-group">
<%= form.label :category %>
<%= form.select :category, [ 'Development', 'Design' ], class: "form-control", :value => params[:category] %>
</div>
<% if current_user.admin === true %>
<%= form.collection_check_boxes(:user_ids, User.where(id: 1).all, :id, :name) do |u| %>
<%= u.label(class: "check_box") { u.check_box(checked: true, class: "add_margin") + u.text } %>
<% end %>
<% end %>
<div class="flex justify-between form-group">
<%= form.button class: "btn btn-primary" %>
<% if form.object.persisted? %>
<%= link_to t("delete"), form.object, class: "btn btn-danger outline", method: :delete, data: { confirm: t("are_you_sure") } %>
<% end %>
</div>
<% end %>
Controller
class TasksController < ApplicationController
before_action :set_task, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
before_action :load_entities, only: :show
# GET /tasks/1/edit
def edit
end
# PATCH/PUT /tasks/1 or /tasks/1.json
def update
respond_to do |format|
if #task.update(task_params)
format.html { redirect_to #task, notice: "Task was successfully updated." }
format.json { render :show, status: :ok, location: #task }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_task
#task = Task.find(params[:id])
puts #task
puts #task.id
end
# Only allow a list of trusted parameters through.
def task_params
params.require(:task).permit(:title, :description, :credits, :deliverydate, :submitteddate, :createdby, :default, :status, :category, :assignedto, user_ids: [])
end
end
Edit:
Adding trace for set_task , example when opening the Edit form for Task ID 7
10:30:24 web.1 | ↳ app/controllers/tasks_controller.rb:91:in `set_task'
10:30:24 web.1 | #<Task:0x000000010d75ddf8>
10:30:24 web.1 | 7
10:30:24 web.1 | Rendering layout layouts/application.html.erb

ID changed to NULL on update - Rails 4

I have a landlord and landlord_address model. When a new landlord_address is created, the landlord_id is saved to the table. For some reason, when I edit a landlord_address the landlord_id is changed to NULL.
Models:
class Landlord < ActiveRecord::Base
has_many :landlord_addresses, dependent: :destroy
belongs_to :listing_agent, class_name: 'Agent'
end
class LandlordAddress < ActiveRecord::Base
belongs_to :landlord
has_many :landlord_companies, dependent: :destroy
end
Landlord Addresses Controller:
module Matrix
class LandlordAddressesController < ApplicationController
before_action :set_landlord_address, only: [:show, :edit, :update, :destroy]
# GET /landlord_addresses
# GET /landlord_addresses.json
def index
#landlord = Landlord.find(params[:landlord_id])
#landlord_addresses = #landlord.landlord_addresses.order(address_line_one: :asc)
end
# GET /landlord_addresses/1
# GET /landlord_addresses/1.json
def show
end
# GET /landlord_addresses/new
def new
#landlord_address = LandlordAddress.new
#landlord = Landlord.find(params[:landlord_id])
end
# GET /landlord_addresses/1/edit
def edit
end
# POST /landlord_addresses
# POST /landlord_addresses.json
def create
#landlord_address = LandlordAddress.new(landlord_address_params)
respond_to do |format|
if #landlord_address.save
format.html { redirect_to matrix_landlord_landlord_addresses_path, notice: 'Landlord address was successfully created.' }
format.json { render :show, status: :created, location: #landlord_address }
else
format.html { render :new }
format.json { render json: #landlord_address.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /landlord_addresses/1
# PATCH/PUT /landlord_addresses/1.json
def update
respond_to do |format|
if #landlord_address.update(landlord_address_params)
format.html { redirect_to matrix_landlord_landlord_addresses_path, notice: 'Landlord address was successfully updated.' }
format.json { render :show, status: :ok, location: #landlord_address }
else
format.html { render :edit }
format.json { render json: #landlord_address.errors, status: :unprocessable_entity }
end
end
end
# DELETE /landlord_addresses/1
# DELETE /landlord_addresses/1.json
def destroy
#landlord_address.destroy
respond_to do |format|
format.html { redirect_to landlord_addresses_url, notice: 'Landlord address was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_landlord_address
#landlord_address = LandlordAddress.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def landlord_address_params
params.require(:landlord_address).permit(:address_line_one, :address_line_two, :city, :state, :zip, :super_name, :super_number, :landlord_id, :latitude, :longitude)
end
end
end
Landlord Addresses _form:
<div class="feedback-container">
<%= form_for [:matrix, #landlord_address] do |f| %>
<% if #landlord_address.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#landlord_address.errors.count, "error") %> prohibited this landlord_address from being saved:</h2>
<ul>
<% #landlord_address.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
/ul>
</div>
<% end %>
<div id="form-map"></div>
<input id="pac-input" class="controls" type="text"
placeholder="Enter a location">
<div id="type-selector" class="controls">
<input type="radio" name="type" id="changetype-all" checked="checked">
<label for="changetype-all">All</label>
</div>
<div class="field">
<%= f.label :address, class: "general-text-label" %>
<%= f.text_field :address_line_one, class: "general-text-field map-autocomplete-address" %>
<%= f.hidden_field :latitude, class: "map-autocomplete-latitude" %>
<%= f.hidden_field :longitude, class: "map-autocomplete-longitude" %>
</div>
<div class="field">
<%= f.label :super_name, class: "general-text-label" %><br>
<%= f.text_field :super_name, class: "general-text-field" %>
</div>
<div class="field">
<%= f.label :super_number, class: "general-text-label" %><br>
<%= f.text_field :super_number, class: "general-text-field" %>
</div>
<div class="field">
<%= f.hidden_field :landlord_id, :value => params[:landlord_id] %>
</div><br>
<div class="actions">
<%= f.submit "Submit", class: "btn btn-black btn-4x" %>
</div>
<% end %>
</div>
Routes:
namespace :matrix do
resources :landlords, shallow: true do
resources :landlord_addresses do
resources :landlord_companies
end
end
end
New Error:
This part
<%= f.hidden_field :landlord_id, :value => params[:landlord_id] %>
will be your issue. When params[:landlord_id] is nil your record will be updated to null.
You should change it to
<%= f.hidden_field :landlord_id, :value => #landlord_address.landlord_id || #landlord.id %>
or some thing else.
Your route is nested, You dnt need to assign in hidden field. You can do it in the controller, passing params.
Form:
Remove hidden field, we are assigning it in the controller!
<div class="field">
<%= f.hidden_field :landlord_id, :value => params[:landlord_id] %>
</div><br>
Controller:
# POST /landlord_addresses
# POST /landlord_addresses.json
def create
#landlord_address = LandlordAddress.new(landlord_address_params)
# add this line here!
#landlord_address.landlord_id = params[:landlord_id]
respond_to do |format|
if #landlord_address.save
format.html { redirect_to matrix_landlord_landlord_addresses_path, notice: 'Landlord address was successfully created.' }
format.json { render :show, status: :created, location: #landlord_address }
else
format.html { render :new }
format.json { render json: #landlord_address.errors, status: :unprocessable_entity }
end
end
end
private
#ALSO REMOVE `:landlord_id` from
def landlord_address_params
params.require(:landlord_address).permit(:address_line_one, :address_line_two, :city, :state, :zip, :super_name, :super_number, :latitude, :longitude)
end

Show nested_fields in Rails 4

I have a weird problem with "nested_form" in Rails. I made a model "evaluate" associated to other model "proyect", but when I try to show theres fields, on "proyects" form, just show fields from "proyects".
Here is my code:
Models:
proyect.erb
class Proyect < ActiveRecord::Base
belongs_to :user
has_many :vercions #I know is versions
has_many :evaluates #I know is evaluators
accepts_nested_attributes_for :evaluates, allow_destroy: true
validates :titulo,:presence => true,
:length => { :minimum => 3 }
validates :descripcion,:presence => true,
:length => { :minimum => 3 }
end
evaluate.erb
class Evaluate < ActiveRecord::Base
belongs_to :proyect
has_and_belongs_to_many :users
end
Controller
proyects_controller.erb
class ProyectsController < ApplicationController
before_action :set_proyect, only: [:show, :edit, :update, :destroy]
# GET /proyects
# GET /proyects.json
def index
if current_user.tipo == 'i'
#proyects = Proyect.where(:user_id => current_user.id)
else
#proyects = #Proyect.where(:id_user => current_user.id)
Proyect.all
end
end
# GET /proyects/1
# GET /proyects/1.json
def show
#vercion = Vercion.new
end
# GET /proyects/new
def new
#proyect = Proyect.new
#proyect.evaluates.build
end
# GET /proyects/1/edit
def edit
end
# POST /proyects
# POST /proyects.json
def create
#proyect = current_user.proyects.new(proyect_params)
respond_to do |format|
if #proyect.save
format.html { redirect_to #proyect, notice: 'Proyecto creado!.' }
format.json { render :show, status: :created, location: #proyect }
else
format.html { render :new }
format.json { render json: #proyect.errors, status: :unprocessable_entity }
end
# Llamamos al ActionMailer que creamos
Usermailer.bienvenido_email(current_user,#proyect).deliver
end
end
# PATCH/PUT /proyects/1
# PATCH/PUT /proyects/1.json
def update
respond_to do |format|
if #proyect.update(proyect_params)
format.html { redirect_to #proyect, notice: 'Proyect was successfully updated.' }
format.json { render :show, status: :ok, location: #proyect }
else
format.html { render :edit }
format.json { render json: #proyect.errors, status: :unprocessable_entity }
end
end
end
# DELETE /proyects/1
# DELETE /proyects/1.json
def destroy
#proyect.destroy
respond_to do |format|
format.html { redirect_to proyects_url, notice: 'Proyect was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_proyect
#proyect = Proyect.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def proyect_params
params.require(:proyect).permit(
:titulo, :descripcion,:evaluador, :id_user, :codigo, :user_assign,evaluates_attributes: [:id,:nombre, :prioridad, :_destroy, user_ids: [] ])
end
end
Views
_form.html.erb (Proyects)
<%= nested_form_for(#proyect) do |f| %>
<% if #proyect.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#proyect.errors.count, "error") %> prohibited this proyect from being saved:</h2>
<ul>
<% #proyect.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :titulo %><br>
<%= f.text_field :titulo %>
</div>
<div class="field">
<%= f.label :descripcion %><br>
<%= f.text_area :descripcion %>
</div>
<div class="field">
<%= f.hidden_field :id_user, :value => current_user.id %>
</div>
<!--Aqui añadi algo-->
<fieldset id="evaluates">
<%= f.fields_for :evaluates do |evaluates_form| %>
<div class="field">
<%= evaluates_form.label :status %><br>
<%= evaluates_form.text_field :status %>
</div>
<%= evaluates_form.link_to_remove "Eliminar esta tarea" %>
<% end %>
<p><%= f.link_to_add "Agregar una tarea", :evaluates %></p>
</fieldset>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
_evaluate_fields.html.erb
<div class="field">
<%= f.label :status, 'Nombre de la tarea' %><br>
<%= f.text_field :status %>
</div>
<div class="field">
<%= f.collection_check_boxes :user_ids, User.where(:tipo => 'e'), :id, :cedula %>
</div>
<%= f.link_to_remove "Eliminar Evaluador" %>

First argument in form cannot contain nil or be empty

I receive this error with my Book form in rails:
First argument in form cannot contain nil or be empty
Form
<%= form_for #book, html: { multipart: true } do |f| %>
<% if #book.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#book.errors.count, "error") %> prohibited this book from being saved:</h2>
<ul>
<% #book.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :author %><br>
<%= f.text_field :author %>
</div>
<div class="field">
<%= f.label :language %><br>
<%= f.text_field :language %>
</div>
<div class="field">
<%= f.label :year %><br>
<%= f.text_field :year %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.label :total_pages %><br>
<%= f.text_field :total_pages %>
</div>
<div class="field">
<%= f.label :rating %><br>
<%= f.text_field :rating %>
</div>
<div class="field">
<%= f.label :image %><br>
<%= f.file_field :image %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Controller
class BooksController < ApplicationController
before_action :set_book, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def search
if params[:search].present?
#books = Book.search(params[:search])
else
#books = Book.all
end
end
def index
#books = Book.all
end
def show
#reviews = Review.where(book_id: #book.id).order("created_at DESC")
if #reviews.blank?
#avg_review = 0
else
#avg_review = #reviews.average(:rating).round(2)
end
end
end
def new
#book = current_user.books.build
end
def edit
end
def create
#book = current_user.books.build(book_params)
respond_to do |format|
if #book.save
format.html { redirect_to #book, notice: 'Book was successfully created.' }
format.json { render :show, status: :created, location: #book }
else
format.html { render :new }
format.json { render json: #book.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #book.update(book_params)
format.html { redirect_to #book, notice: 'Book was successfully updated.' }
format.json { render :show, status: :ok, location: #book }
else
format.html { render :edit }
format.json { render json: #book.errors, status: :unprocessable_entity }
end
end
end
def destroy
#book.destroy
respond_to do |format|
format.html { redirect_to books_url, notice: 'Book was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_book
#book = Book.find(params[:id])
end
def book_params
params.require(:book).permit(:title, :author, :language, :year, :description, :total_pages, :rating, :image)
end
I got related errors, but none of the solutions seems to fit my particular issue. Any clues to what could be causing this?
You're getting the error because #book is nil.
Make sure that you have initialized #book using #book = Book.new in the corresponding controller action so that #book is available to the view containing the form.
initialized #book = Book.new in the controller action

presence validation causes "undefined method `map' for nil:NilClass" error

I want people to define a course name before writing a spotlight. I did this by adding following code to the spotlight model
class Spotlight < ActiveRecord::Base
validates :name, presence: true
end
Before adding the validation I could write spotlights without any name. If I try that now I get following error message:
undefined method `map' for nil:NilClass
Extracted source (around line #29):
</div>
<div class="field">
<%= f.label :name, "Opleiding" %><br>
<%= f.collection_select(:name, #colli, :name, :name, {prompt: 'Selecteer een opleiding'}, {id: 'collis_select'}) %>
</div>
<div class="field">
<%= f.label :teaser %><br>
What is going on here? The collection select is the base for an ajax call I do to fill up other fields.
View
<%= form_for(#spotlight) do |f| %>
<% if #spotlight.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#spotlight.errors.count, "error") %> prohibited this spotlight from being saved:</h2>
<ul>
<% #spotlight.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :spotlight, "In de kijker" %><br>
<%= f.check_box :spotlight %>
</div>
<div class="field">
<%= f.label :start, "Start in de kijker" %><br>
<%= f.datetime_select :start %>
</div>
<div class="field">
ruby-on-rails
<%= f.label :stop, "Stop in de kijker" %><br>
<%= f.datetime_select :stop %>
</div>
<div class="field">
<%= f.label :name, "Opleiding" %><br>
<%= f.collection_select(:name, #colli, :name, :name, {prompt: 'Selecteer een opleiding'}, {id: 'collis_select'}) %>
</div>
<div class="field">
<%= f.label :teaser %><br>
<%= f.text_area :teaser, size: "85x10", id: 'teasers_select' %>
</div>
<div class="field">
<%= f.label :coursedate, "Startdatum opleiding" %><br>
<%= f.datetime_select :coursedate, id: 'startdate_select' %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<script>
$(document).ready(function() {
$('#collis_select').change(function() {
$.ajax({
url: "<%= update_teasers_path %>",
data: {
name : $('#collis_select').val()
},
dataType: "script"
});
});
});
</script>
Update teaser view
$('#teasers_select').val("<%= escape_javascript(#teaser) %>");
Controller
class SpotlightsController < ApplicationController
before_action :set_spotlight, only: [:show, :edit, :update, :destroy]
before_action :load_colli, only: [:new, :edit]
def index
#spotlights = Spotlight.all.order('spotlight DESC, start, stop')
end
def show
end
def new
#spotlight = Spotlight.new
end
def edit
end
def create
#spotlight = Spotlight.new(spotlight_params)
respond_to do |format|
if #spotlight.save
format.html { redirect_to #spotlight, notice: 'Spotlight was successfully created.' }
format.json { render action: 'show', status: :created, location: #spotlight }
else
format.html { render action: 'new' }
format.json { render json: #spotlight.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #spotlight.update(spotlight_params)
format.html { redirect_to #spotlight, notice: 'Spotlight was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #spotlight.errors, status: :unprocessable_entity }
end
end
end
def update_teasers
# updates artists and songs based on genre selected
colli = Colli.where(name: params[:name])
# map to name and id for use in our options_for_select
#teaser = colli.first.teaser
end
def destroy
#spotlight.destroy
respond_to do |format|
format.html { redirect_to spotlights_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_spotlight
#spotlight = Spotlight.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def spotlight_params
params.require(:spotlight).permit(:spotlight, :start, :stop, :name, :teaser, :coursedate)
end
def load_colli
#colli = Colli.select(:name).distinct.order('name')
end
end
Can somebody explain what seems to be the problem? What is the "map" function the error is referring to?
It looks like your #colli object is nil.
<%= f.collection_select(:name, #colli, :name, :name, {prompt: 'Selecteer een opleiding'}, {id: 'collis_select'}) %>
This has nothing to do with the presence validation. Make sure the collection_select method is receiving a #colli instance variable. Right now it's receiving nil.
The map function is an instance method in the class Array. It receives a block, iterates over an array, and returns a new array with elements returned from the block. You can't call map on nil; you will get the error you are seeing above.
You can check if #colli is nil by raising it:
def load_colli
#colli = Colli.select(:name).distinct.order('name')
raise #colli.to_s
end
If you change the update_teasers function to:
def update_teasers
# updates artists and songs based on genre selected
#colli = Colli.where(name: params[:name])
# map to name and id for use in our options_for_select
#teaser = #colli.first.teaser
end
that should fix the issue. This isn't an issue with the presence validation.
EDIT:Sorry, that didn't work. Next I would try to set the #colli variable in the create function as follows. That way the variable is still set when it renders the new action upon a failed save.
def create
#spotlight = Spotlight.new(spotlight_params)
#colli = Colli.where(name: params[:name])
respond_to do |format|
if #spotlight.save
format.html { redirect_to #spotlight, notice: 'Spotlight was successfully created.' }
format.json { render action: 'show', status: :created, location: #spotlight }
else
format.html { render action: 'new' }
format.json { render json: #spotlight.errors, status: :unprocessable_entity }
end
end
end

Resources