I've got a problem with the creation of an object. The New-function ist working, but when i pass the object to the Create, the following error is thrown.
I want to add a Service when a ServiceProvider exists. Every User can create one ServiceProvider for himself. A ServiceProvider could have a few services.
I've also set the foreign-keys for the services-table in a MIgration-file via
"add_foreign_key :services, :service_provider"
I don't have an idea why the service_provider_id isn't transfered.
Error Output
ActiveRecord::RecordNotFound in ServicesController#create
Couldn't find ServiceProvider with 'id'=
Extracted source (around line #55):
private
def current_service_provider
Line 55: #current_service_provider = ServiceProvider.find(params[:id])
end
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"Z4s/ZzbbMmcXA1jAyFnEZZ/8RhS2ZO/UdI6xN5QkKQwXmJJOOo/PVsSdOUcuJvVpFJdaUi/rMtNJq5sAEdz89g==",
"service"=>{"name"=>"dsfg", "address"=>"asdf", "radius"=>"64655", "price"=>"45", "descr"=>"sdfagasrfsdgh"},
"commit"=>"Speichern"}
Models
class ServiceProvider < ApplicationRecord
belongs_to :user
has_many :services
validates :name, presence: true
validates :street, presence: true
validates :plz, presence: true
validates :location, presence: true
validates :user_id, presence: true
end
class Service < ApplicationRecord
belongs_to :service_provider
has_many :service_photos
validates :name, presence: true, length: {maximum: 50}
validates :address, presence: true
validates :price, presence: true
end
ServicesController
class ServicesController < ApplicationController
before_action :set_service, only: [:show, :edit, :update]
before_action :authenticate_user!, except: [:show]
def index
#service = current_user.services
end
def show
#service_photos = #service.service_photos
end
def new
#service = Service.new
end
def create
#service = current_service_provider.services.build(service_params)
if #service.save
if params[:images]
params[:images].each do |image|
service.service_photos.create(image: image)
end
end
#service_photos = #service.service_photos
redirect_to edit_service_path(#service), notice: "Gespeichert"
else
render :new
end
end
def edit
end
def update
end
private
def current_service_provider
#current_service_provider = ServiceProvider.find(params[:id])
end
def set_service
#service = Service.find(params[:id])
end
def service_params
params.require(:service).permit(:name, :address, :radius, :price, :descr)
end
end
Form
<div class="panel panel-default">
<div class="panel-heading">
Erstelle deinen Service
</div>
<div class="panel-body">
<div class="container">
<%= form_for #service, html: {multipart: true} do |f| %>
<div class="row">
<div class="form-group">
<label>Service Name</label>
<%= f.text_field :name, placeholder: "Servicename", class: "form-control" %>
</div>
</div>
<div class="row">
<div class="form-group">
<label>Adresse</label>
<%= f.text_field :address, placeholder: "Adresse", class: "form-control" %>
</div>
</div>
<div class="row">
<div class="form-group">
<label>Radius</label>
<%= f.text_field :radius, placeholder: "Radius", class: "form-control" %>
</div>
</div>
<div class="row">
<div class="form-group">
<label>Preis</label>
<%= f.text_field :price, placeholder: "Preis", class: "form-control" %>
</div>
</div>
<div class="row">
<div class="form-group">
<label>Beschreibung</label>
<%= f.text_area :descr, rows: 5, placeholder: "Beschreibung", class: "form-control" %>
</div>
</div>
<div class="rows">
<div class="col-md-4">
<div-form-group>
<span class="btn btn-default btn-file">
<i class="fa fa-cloud-upload fa-lg"></i>Fotos hochladen
<%= file_field_tag "images[]", type: :file, multiple: true %>
</span>
</div-form-group>
</div>
</div>
<div id="photos"><%= render 'service_photos/list' %></div>
<div class="actions">
<%= f.submit "Speichern", class: "btn btn-primary" %>
</div>
<% end %>
</div>
</div>
</div>
In "create" action you try to find non-existing object. You can find object by 'id' after save that.
In your case params[:id] is not exist when "current_service_provider" method is calling.
Related
Hello rails community!
I have booking_post model that has_many reservations.
class BookingPost < ApplicationRecord
has_many :reservations, dependent: :destroy
end
All reservation belongs_to booking_post and have some validations
class Reservation < ApplicationRecord
belongs_to :booking_post
before_save { self.email = email.downcase }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX }
validates :name, :email, :phone_number, :start, :end, presence: true
end
My routes are next:
resources :booking_posts do
resources :reservations, only: [:new, :create]
end
Methods:
class BookingPostsController < ApplicationController
def show
#booking_picture = #booking_post.booking_pictures.build
#booking_pictures = #booking_post.booking_pictures
#reservation = #booking_post.reservations.build
#reservations = #booking_post.reservations
end
end
class ReservationsController < ApplicationController
def new
#reservation = Reservation.new
end
def create
#booking_post = BookingPost.find(params[:booking_post_id])
#email= User.where(admin: true).first.email
#reservation = #booking_post.reservations.build(reservation_params)
if #reservation.save
#saved_reservation = #reservation
redirect_to :back
flash[:notice] = 'Reservation was successfully created.'
ReservationMailer.fresh_message(#saved_reservation, #email).deliver_now
else
redirect_to #booking_post
flash[:info] = #reservation.errors.full_messages do |m|
m
end
end
end
end
I would like to create on booking_posts/show.html.erb form_for #reservation, and render on this page errors for #reservation. When I create valid #reservation, I see on booking_posts/show.html.erb successfull flash message, but unvalid #reservation appear without any error flash messages.
form_for #reservation on booking_posts/show.html.erb:
<div class="card-action">
<%= form_for([#reservation.booking_post, #reservation], html: {multipart: true}, class: "col s12") do |f| %>
<% if #reservation.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#reservation.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% #reservation.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="col s6">
<%= f.label :start %>
<%= f.date_field :start, placeholder: "start time", class: "datepicker" %>
</div>
<div class="col s6">
<%= f.label :end %>
<%= f.date_field :end, placeholder: "end time", class: "datepicker" %>
</div>
<div class="col s6">
<%= f.label :reservation_time %>
<%= f.time_field :reservation_time, placeholder: "time", class: "timepicker", id: "timepicker", type: "time" %>
</div>
<div class="input-field col s6">
<%= f.label :name %>
<%= f.text_field :name, class: "validate" %>
</div>
<div class="input-field col s6">
<%= f.label :email %>
<%= f.text_field :email, class: "validate" %>
</div>
<div class="input-field col s6">
<%= f.label :phone_number %>
<%= f.text_field :phone_number, class: "validate" %>
</div>
<div class="waves-effect waves-light btn">
<%= f.submit t(:submit_reservation)%>
</div>
<% end %>
<br>
</div>
I would like render error messages for #reservation on #booking_post page
(in booking_post_path, not in new_reservation_path or anyting else). How can I do so?
Thanks for solutions
In your else block, Please update it like this
flash[:notice] = #reservation.errors.full_messages.to_sentence
redirect_to #booking_post
I have two model:
1.Personne
class Personne < ApplicationRecord
has_one :proprietaire
accepts_nested_attributes_for :proprietaire
validates :nom, :prenom, :tel, :email,
presence: true
end
2 Proprietaire
class Proprietaire < ApplicationRecord
belongs_to :personne
validates :commune_id, :quartier,
presence: true
end
the Controller is:
class PersonneController < ApplicationController
def display_proprietaires
#proprietaires = Personne.all
##proprietaires = #proprietaires.proprietaire
end
def new_proprietaire
#provinces = Province.where(:parentId => nil)
#communes = Province.where.not(:parentId => nil)
#personne = Personne.new
#personne.build_proprietaire
end
def create_proprietaire
#proprietaire = Personne.new(proprietaire_params)
#proprietaire.build_proprietaire
respond_to do |format|
if #proprietaire.save
flash[:notice] = "succes"
flash[:type] = "success"
format.html { redirect_to action: :display_proprietaires }
else
flash[:notice] = "fail"
flash[:type] = "warning"
format.html { redirect_to action: :display_proprietaires }
end
end
end
def proprietaire_params
params.require(:personne).permit(:nom, :prenom, :tel, :email, proprietaire_attributes: [:id, :commune_id, :quartier]).except(:province, :commit)
end
end
the View is:
<%= form_for #personne, :url => url_for(:controller=>'personne', :action=>'create_proprietaire' ) do |f| %>
<div class="row">
<div class="col-xs-6 col-sm-6 col-lg-6">
<div class="form-group">
<%= f.label(:nom, 'Nom : ') %>
<%= f.text_field :nom, {class: "form-control", placeholder: 'Nom'} %>
</div>
<div class="form-group">
<%= f.label(:prenom, 'Prenom : ')%>
<%= f.text_field :prenom, {class: "form-control", placeholder: "Prenom"} %>
</div>
<div class="form-group">
<%= f.label(:tel, 'Telephone : ')%>
<%= f.text_field :tel, {class: "form-control", placeholder: "Telephone"} %>
</div>
<div class="form-group">
<%= f.label(:email, 'Email : ') %>
<%= f.text_field :email, {class: "form-control", placeholder: "Email"} %>
</div>
<div class="form-group">
<%= label_tag(:province, 'Province : ') %>
<%= select_tag(:province, options_for_select(#provinces.collect{|value| [value.denomination, value.id]}), {class: "form-control", id: "province", remote: true} ) %>
</div>
<%= f.fields_for :proprietaire do |proprio| %>
<div class="form-group">
<%= proprio.label(:commune_id, 'Commune : ') %>
<%= proprio.select :commune_id, options_for_select(#communes.collect{|value| [value.denomination, value.id]}),{}, {class: "form-control", id: "commune"} %>
</div>
<div class="form-group">
<%= proprio.label :quartier, "Quartier" %>
<%= proprio.text_field :quartier, {class: "form-control", placeholder: "Quartier"} %>
</div>
<% end %>
<%= f.submit "Enregistre", {class: 'btn btn-info'} %>
<% end %>
Routes:
resources :personne do
collection do
post :create_proprietaire
get :display_proprietaires
get :new_proprietaire
end
end
I'm new in RoR, When I try to save nothing happens, I'm getting this:
Could someone helps me on this. Thank you!
You have your association set to required but it's missing.
Associations are set to required by default in rails 5 so if you want to keep one empty you need to set optional:true on your association in model
I'm very frustrated because I've been working on it for days and I haven't found a solution yet.
I have a Visit.rb model and, beyond the common validations, I have two more validations through two methods of mine (visit's start date cannot be prior to end one and there's no possibility to have two visits having the same start date, end date and visitor_id).
I need to show these errors set by me in the modal I'm giving to register a visit, but until now I've never had success.
In fact every time this error occurs: ArgumentError in VisitsController#create - First argument in form cannot contain nil or be empty
Here what I've done until now is...
Visit.rb
class Visit < ActiveRecord::Base
belongs_to :employee
belongs_to :visitor
default_scope -> { order(:created_at) }
validates :from, presence: true, uniqueness: { scope: [:to, :visitor_id] }
validates :to, presence: true
validates :visitor_id, presence: true
validates :employee_id, presence: true
validate :valid_date_range_required
validate :visit_uniqueness
def valid_date_range_required
if (from && to) && (to < from)
errors[:base] << "Visit's end date cannot be prior to the start one."
end
end
def visit_uniqueness
if Visit.find_by(from: :from, to: :to, visitor_id: :visitor_id)
errors[:base] << "A visit with the same start date, end date and visitor already exists."
end
end
end
visits_controller.rb
class VisitsController < ApplicationController
before_action :logged_in_employee, only: [:create, :destroy]
before_action :correct_employee, only: [:destroy, :update ]
def create
#visit = current_employee.visits.build(visit_params)
if #visit.save
flash[:success] = "Visit added"
redirect_to employee_path(session[:employee_id], :act => 'guestsVisits')
else
#visits = current_employee.visits.all
#employee = current_employee
render 'employees/guestsVisits'
end
end
private
def visit_params
params.require(:visit).permit(:from, :to, :visitor_id, :employee_id)
end
def correct_employee
#visit = current_employee.visits.find_by(id: params[:id])
redirect_to root_url if #visit.nil?
end
end
guestsVisits.rb (my view)
<div class="jumbotron3 text-center">
<div class="row">
<h1>Guests Visits</h1>
<hr>
<%=render :partial =>"layouts/sidebar"%>
<div class="panel3">
<div class="panel-body">
<!-- Modal for Visit -->
<% if logged_in? %>
<%=render :partial =>"shared/error_messages"%>
<a class="btn icon-btn btn-success pos" data-toggle="modal" data-target="#visitModal">
<span class="glyphicon btn-glyphicon glyphicon-plus img-circle text-success"></span>
Add a visit
</a>
<div id="visitModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Visit</h4>
</div>
<div class="modal-body">
<%= form_for(#visit) do |f| %>
<%= f.label :start_date %>
<%= f.date_field :from, class: 'form-control',:value => (f.object.from.strftime('%m/%d/%Y') if f.object.from) %>
<%= errors_for #visit, :from %><%if #visit.errors.any?%><br><%end%>
<br>
<%= f.label :end_date %>
<%= f.date_field :to, class: 'form-control',:value => (f.object.to.strftime('%m/%d/%Y') if f.object.to) %>
<%= errors_for #visit, :to %><%if #visit.errors.any?%><br><%end%>
<br>
<%= f.label :Visitor %>
<%= f.collection_select :visitor_id, Visitor.all, :id, :full_name, { :class=> "form-control", :include_blank => ''}%>
<%= errors_for #visit, :visitor_id %><%if #visit.errors.any?%><br><%end%>
<br>
<%= f.submit "Add visit", class: "btn btn-primary btn-color" %>
<% end %>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-info" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<% end %>
</div>
</div>
</div>
</div>
I tried to use two different versions of error_messages.rb
error_messages.rb (1)
<% if #visit && #visit.errors.any? %>
<div id="error_explanation">
<div class="alert alert-danger">
×
The form contains <%= pluralize(#visit.errors.count, "error") %>.Open the modal for more details
</div>
</div>
<% end %>
error_messages.rb (2)
<% if #visit.errors.any? %>
<ul class="errors">
<% #visit.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
I hope someone can help me because I don't understand how to figure it out.
Thank you a lot.
EDIT:
class Employee < ActiveRecord::Base
before_save { self.email = email.downcase }
before_create :confirmation_token
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
has_many :macaddresss, dependent: :destroy
has_many :visits, dependent: :destroy
has_many :visitors, dependent: :destroy
#Validations
validates :name, presence: true , length: { maximum:20 , minimum: 2 }
validates :lastname, presence: true, length: { maximum:20 , minimum: 2 }
validates :gender, presence: true
validates :dateofbirth, presence: true
validates :birth_country, presence: true
validates :birth_place, presence: true, length: { maximum:60}
validates :contry_of_residence, presence: true
validates :city_of_residence, presence: true, length: { maximum:60 }
validates :address, presence: true, length: { maximum:60 , minimum: 7 }
validates :email, presence: true, length: { maximum:243 } ,format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
validates :password, length: { minimum: 6 }
validates :terms_of_service, acceptance: { message: 'accept terms and conditions' }
[...]
has_secure_password
def Employee.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
end
session_helper.rb
def current_employee
#current_employee ||= Employee.find_by(id: session[:employee_id])
end
EDIT2:
employees_controller.rb
class EmployeesController < ApplicationController
def show
if logged_in?
#employee = Employee.find(params[:id])
#indirizzimac = current_employee.indirizzimacs.new
#visitor = current_employee.visitors.new
#visit = current_employee.visits.new
#visits = current_employee.visits.all
if params[:act]=='myData'
render 'myData'
elsif params[:act]=='myNetwork'
render 'myData'
elsif params[:act]=='temporaryUsers'
render 'temporaryUsers'
elsif params[:act]=='guestsVisits'
render 'guestsVisits'
elsif params[:act]=='myAccount'
render 'myAccount'
else
render 'show'
end
else
render 'static_pages/errorPage'
end
end
end
From what i can see if creating visit fails you instantiate #visits and #employee instance variables then rendering 'employees/guestsVisits' its view you use #visit which i think it doesn't exist inside empleyees controller
So add it ad
def guestsVisits
#visit = current_employee.visits.build
end
I have this form in rails, in my view new.html.erb
<%= form_for( #rent , html: { class: 'form-horizontal' }) do |f| %>
<div class="form-group">
<label for="" class="col-lg-2 col-md-3 col-sm-3 col-xs-3 control-label">year:</label>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
<%= f.text_field :year, class: 'form-control' %>
</div>
<div class="col-lg-2 col-md-3 col-sm-3 col-xs-3">
<%= f.submit 'Buscar', :class =>"btn btn-sm btn-info btn-flat" %>
</div>
<div class="clearfix"></div>
</div>
<% end %>
<%= render 'shared/error_messages', object: #rent %>
In my controller I have this
class RentsController < ApplicationController
def new
#rent = RentSearch.new
end
private
def search_params
params.require(:year).permit(:year)
end
end
In my model, had this code:
class RentSearch
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :year
validates :year, presence: true
validates :year, length: { is: 4 }
end
With this code I get this error
undefined method `persisted?' for #
But I made some modifications and not show error, but when submit not display any error and form is empty, I don't know how can solve this.
What is the best way to create a form in rails without model access to database and passing all validations to the controller and verify.
MY SOLUTION
Thanks to #Зелёный for help.
route.rb
resources :rents, only: [:index, :new, :create]
rent.rb - model
class Rent
# Validations
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :year
validates :year, presence: true
validates :year, length: { is: 4 }
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false # which means this object persisted in the database.
end
end
rents_controller.rb
class RentsController < ApplicationController
def index
#params = params
end
def new
#rent = Rent.new
end
def create
#rent = Rent.new( params['/rents'] )
if #rent.valid?
redirect_to tg_rents_path( year: params['/rents']['year'] )
else
render :action => 'new'
end
end
end
new.html.erb
<%= form_for( tg_rents_path , url: {action: "create"}, html: { class: 'form-horizontal' }) do |f| %>
<div class="form-group">
<label for="" class="col-lg-2 col-md-3 col-sm-3 col-xs-3 control-label">year:</label>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
<%= f.text_field :year, class: 'form-control' %>
</div>
<div class="col-lg-2 col-md-3 col-sm-3 col-xs-3">
<%= f.submit 'Search', :class =>"btn btn-sm btn-info btn-flat" %>
</div>
<div class="clearfix"></div>
</div>
<% end %>
<%= render 'shared/error_messages', object: #rent %>
Thanks to all!!
i have a problem with my form who contains multiple object
When i go on my page "new" for create new team_member, i have this error :
unknown attribute 'team_member_id' for TeamMembersGame.
models/team_member.rb
class TeamMember < ActiveRecord::Base
mount_uploader :avatar, AvatarUploader
has_many :team_members_games
accepts_nested_attributes_for :team_members_games
has_many :team_members_weapons
has_many :team_members_champions
end
models/team_member_game.rb
class TeamMembersGame < ActiveRecord::Base
belongs_to :team_member
end
controllers/admin/team_members_controller.rb
class Admin::TeamMembersController < Admin::DashboardController
def new
#member = TeamMember.new
#member.team_members_games.build
end
def create
#member = TeamMember.new(member_params)
if #member.save
redirect_to edit_admin_team_member_path(#member.id), notice: 'Le membre a bien été creer'
else
render 'new'
end
end
def edit
#member = TeamMember.find(params[:id])
#member_game = #member.team_members_games
##member = TeamMember.joins(:TeamMembersChampion, :TeamMembersWeapon, :TeamMembersGame)
end
def update
#member = TeamMember.find(params[:id])
if #member.update_attributes(member_params)
# Handle a successful update.
redirect_to edit_admin_team_member_path(#member.id), notice: 'Le membre a bien été modifier'
else
render 'edit'
end
end
def destroy
TeamMember.destroy(params[:id])
redirect_to admin_team_members_path, notice: 'Le membre a bien ete supprimer'
end
private
def member_params
params.require(:team_member).permit(:name, :id_steam, :color, :avatar, :avatar_color, :description, :rank_cs, :rank_lol, :role_cs, :role_lol, team_members_games: [ :team_members_id, :name_game])
end
def member_games
params.require(:team_members_games).permit(:team_members_id, :name_game)
end
end
view/admin/new.html.erb
<%= form_for(#member, url: admin_team_members_path, html: { method: :post }, id: 'new_news') do |f| %>
<%= #member.inspect %>
<%= #member_games.inspect %>
<div class="row">
<div class="col s12">
<% #member.errors.full_messages.each do |msg| %>
<%= msg %>
<% end %>
</div>
</div>
<div class="row">
<div class="col s12 m6">
<div class="field input-field">
<%= f.label :name, "Nom" %>
<%= f.text_field :name, autofocus: true, :class => "" %>
</div>
</div>
</div>
<div class="row">
<div class="col s12">
<p class="bold">
Jeux :
</p>
</div>
<div class="col s12 m6">
<%= f.fields_for :team_members_games do |team_members_games_form| %>
<div class="field input-field">
<%= team_members_games_form.check_box :name_game, {:class => "filled-in", :id => "team_members_game_name_game"}, true, false %>
<%= team_members_games_form.label :name_game, "game" %>
</div>
<% end %>
</div>
</div>
<div class="row">
<div class="col s12">
<div class="btnlog actions">
<%= button_tag(type: 'submit', class: "btn") do %>
Publier <i class='material-icons right'>send</i>
<% end %>
</div>
</div>
</div>
<% end %>
thanks !
you are permitting team_members_id in your code instead of team_member_id
refactor your code to this:
def member_params
params.require(:team_member).permit(:name, :id_steam, :color, :avatar, :avatar_color, :description, :rank_cs, :rank_lol, :role_cs, :role_lol, team_members_games_attributes: [ :id, :team_member_id, :name_game])
end
Change permitted method name and parameters like this:-
def team_member_params
params.require(:team_member).permit(:name, :id_steam, :color, :avatar, :avatar_color, :description, :rank_cs, :rank_lol, :role_cs, :role_lol, team_members_games: [ :id, :name_game])
end
And use this method while creating team member:-
def create
#member = TeamMember.new(team_member_params)
if #member.save
redirect_to edit_admin_team_member_path(#member.id), notice: 'Le membre a bien été creer'
else
render 'new'
end
end
I have corrige some errors, but i haven't idea for get the id of team_member for the table team_member_games :
def team_member_params
params.require(:team_member).permit(:name, :id_steam, :color, :avatar, :avatar_color, :description, :rank_cs, :rank_lol, :role_cs, :role_lol, team_members_game_attributes: [ :id, :name_game])
end
no one element are add in my table team_members_games