I have created a form but I'm having issues submitting the form, it's not getting the right route, I'm sure this is a simple fix, I'm just not seeing it.
Here are the relevant files:
new.html.erb
<%= content_for :title, "Orders & Returns" %>
<div class="title">
<h1>Orders & Returns</h1>
<p>In order for us to initialise a return of any order, first we need some information.</p>
</div>
<%= simple_form_for("/orders_and_returns/thank_you") do |f| %>
<%= f.input :order_number,
error: false,
label: false,
required: true,
placeholder: "Order Number" %>
<%= f.input :billing_name,
error: false,
label: false,
required: true,
placeholder: "Billing Name" %>
<%= f.input :email,
error: false,
label: false,
required: true,
placeholder: "Email Address" %>
<%= f.input :message,
as: :text,
error: false,
label: false,
required: true,
placeholder: "Why do you wish to initialise a return?" %>
<div class="hidden">
<%= f.input :nickname,
label: false,
required: false,
placeholder: "Captcha" %>
</div>
<%= f.submit "Submit",
class: "button-border center-100" %>
<% end %>
thank_you.html.erb
<% content_for :title, "Thank You" %>
<div class="title">
<h3>Thank you for your message!</h3>
<p>We shall get back to you soon.</p>
</div>
<section class="text-center">
<%= link_to "Go back home", root_path %>
</section>
order_and_returns_controller.rb
class OrdersAndReturnsController < ApplicationController
def new
end
def thank_you
#order_name = params[:order_name]
#billing_name = params[:billing_name]
#email = params[:email]
#message = params[:message]
OrdersAndReturnMailer.orders_and_returns(#order_number, #billing_name, #email, #message).deliver_now
end
end
orders_and_return_mailer.rb
class OrdersAndReturnMailer < ApplicationMailer
def orders_and_returns(order_number, billing_name, email, message)
#order_number = order_number
#billing_name = billing_name
#email = email
#message = message
mail(
from: email,
to: ENV['order_email'],
subject: "You have a new return query from #{email}"
)
end
end
end
routes.rb
get 'orders_and_returns/new'
post 'orders_and_returns/thank_you'
Not sure what I'm missing here, any help would be appreciated.
You must point the route to the controller and action
get 'orders_and_returns/new' => 'orders_and_returns#new'
post 'orders_and_returns/thank_you' => 'orders_and_returns#thank_you'
Related
I'm having issues with a form in my Rails 6 application.
I have a remote form which enters new data into the database via a JSON request, which works but only with one parameter. This is the form:
<%= form_with(method: :post, remote: true, model: Meal.new, url: meals_path, class: "editMealsForm", data: { type: "json" }) do |f| %>
<div class="field">
<%= f.label :description, 'Beschreibung' %><br>
<%= f.text_area :description, rows: "4", placeholder: "Noch keine Mahlzeit für diesen Tag vorhanden, bitte eintragen!", class: "form-control" %>
</div>
<div class="field">
<%= f.label :allergene_ids_add, 'Allergene auswählen', class: "card-text" %><br>
<%= select_tag :allergene_ids_add, options_from_collection_for_select(#allergenes, :id, :name), multiple: true, class: "selectpicker", data: { style: "btn-success", width: "fit", live_search: "true", size: "5", title: "Allergien wählen" } %>
</div>
<% f.hidden_field :day, :value => local_assigns[:mealDay] %>
<% f.hidden_field :tip, :value => "Vollkost" %>
<%= f.submit "Speichern", class: "btn btn-primary mt-2 btn-block" %>
<% end %>
And these are my permitted parameters:
def meal_params
params.require(:meal).permit(:day, :tip, :description, allergene_ids_add: [])
end
And this is my controller action:
def create
#meal = Meal.new(meal_params)
byebug
if #meal.save
if params[:allergene_ids_add].present?
#allergenes_to_add = Allergene.find(params[:allergene_ids_add])
#allergenes_to_add.each do |allergene|
#meal.allergenes << allergene
end
end
respond_to do |format|
format.html { redirect_to meals_path }
format.json { render json: #meal }
end
end
end
The problem is, that if I hit the create action, just the description parameter is permitted, the other ones are just "ignored", so if I fire the submit button I get the following output in the console if I hit my byebug breakpoint:
And if I look at the params:
<ActionController::Parameters {"authenticity_token"=>"derBZeirq0bwr/FWoYRr97qUZ5p66vQc+uT+UMf5xjXXTSFEp+XOepJtGrckguGh+skWXTZ9ibHWfFTt3p80Cg==", "meal"=><ActionController::Parameters {"description"=>"test"} permitted: false>, "commit"=>"Speichern", "controller"=>"meals", "action"=>"create"} permitted: false>
Or just at the meal params:
<ActionController::Parameters {"description"=>"test"} permitted: true>
If I run #meal.valid? it returns true, so I don't see where the issue is.
Also if I check the values for the hidden fields in the form, they are filled and not nil.
So why does this one parameter work, but the rest just isn't permitted even if I got them in my meal_params method?
Okay, I am dumb.
I just forgot the = for the hidden fields.
So instead of:
<% f.hidden_field :day, :value => local_assigns[:mealDay] %>
<% f.hidden_field :tip, :value => "Vollkost" %>
it should be:
<%= f.hidden_field :day, :value => local_assigns[:mealDay] %>
<%= f.hidden_field :tip, :value => "Vollkost" %>
Then everything is working.
When I try to create an "Action" I get this error.
My Actions controller:
class ActionsController < ApplicationController
def new
#match_set = MatchSet.find(params[:match_set_id])
#fixture = #match_set.fixture
#teams = Team.where("id = " + #fixture.home_team_id.to_s + " OR id = " + #fixture.away_team_id.to_s)
#players = Player.where("team_id = " + #teams.ids.first.to_s + " OR id = " + #teams.ids.last.to_s)
#action = #match_set.actions.new
end
def create
#match_set = MatchSet.find(params[:match_set_id])
#action = #match_set.actions.new(action_params)
if #action.save
redirect_to match_set(#match_set)
else
render "actions/new"
end
end
private
def action_params
params.require(:action).permit(:team_id, :player_id, :position, :action_type, :action_result)
end
end
It is submitted from this form in views/actions/new.html.erb:
<%= form_for [#match_set, #action] do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<!-- Team -->
<%= f.label :team_id %>
<%= f.collection_select :team_id, #teams,:id, :name, {include_blank: "Select team..."}, {class: "form-control"} %>
<!-- Player -->
<%= f.label :player_id %>
<%= f.collection_select :player_id, #players,:id, :last_name, {include_blank: "Select player..."}, {class: "form-control"} %>
<!-- Position -->
<%= f.label :position %>
<%= f.select :position, options_for_select(['1', '2', '3', '4', '5', '6']), {include_blank: "Select position on court..."}, class: "form-control" %>
<!-- Action Type -->
<%= f.label :action_type %>
<%= f.select :action_type, options_for_select(['Attack', 'Block', 'Pass', 'Set']), {include_blank: "Select action_type..."}, class: "form-control" %>
<!-- Action Result -->
<%= f.label :action_result %>
<%= f.select :action_result, options_for_select(['Score', 'Block', 'Pass', 'Set']), {include_blank: "Select action_type..."}, class: "form-control" %>
<!-- Submit Button -->
<%= f.submit "Add Action", class: "btn btn-primary" %>
<% end %>
Also the relevant routes:
resources :fixtures, shallow: true do
resources :match_sets, shallow: true do
resources :actions
end
end
I'm getting an error on this line in the controller:
params.require(:action).permit(:team_id,:player_id,
:position,:action_type,:action_result)
I have also noticed that my parameters seem to be disappearing but again have no clue as to the cause.
Parameters:
{"utf8"=>"✓", "authenticity_token"=>"BqbEOfL7hEA8XSMXDvMW2qQ2uR74Egp5
jJvtQlsuyV2TikZJ+6hTIEMH05gy8TM6r3ZglFDRUFBl7ScZD1czCQ==",
"commit"=>"Add Action", "match_set_id"=>"15"}
Any help is appreciated.
action is a reserved word in rails. You will need to change your model name.
Rails provides a few params on each request such as:
params[:controller] # maps to your controller name
params[:action] # maps to an action with your controllers
http://api.rubyonrails.org/classes/ActionDispatch/Routing.html
I'm starting in rails and I have this error that I'm not able to solve..
Error - param is missing or the value is empty:
personas_x_tipos_persona
Controller
class PersonasController < ApplicationController
def create_cliente
#cliente = Persona.new(persona_params)
#personas_x_tipos_personas = Persona.new(tipos_personas_params)
if #cliente.save
redirect_to show_clientes_path
else
render :new_cliente
end
end
private
def persona_params
params.require(:persona).permit(:nombre, :apellido, :direccion, :ruc, :contacto, :email)
end
def tipos_personas_params
params.require(:personas_x_tipos_persona).permit(:linea_credito)
end
end
view
<div>
<%= form_for :persona ,:url => add_cliente_path, :html => {:method => :post} do |f|%>
<% #cliente.errors.full_messages.each do |message| %>
<div class="alert alert-danger" margin-top:10px">
* <%=message%>
</div>
<% end %>
<%= f.text_field :nombre, placeholder: "Nombre del Cliente"%>
<%= f.text_field :apellido, placeholder: "Apellido del Cliente"%>
<%= f.text_field :direccion, placeholder: "Direccion del Cliente"%>
<%= f.text_field :ruc, placeholder: "RUC del Cliente"%>
<%= f.text_field :contacto, placeholder: "Contacto del Cliente"%>
<%= f.email_field :email, placeholder: "Email del Cliente""%>
<%= f.fields_for :personas_x_tipos_persona do |pxp|%>
<%= pxp.number_field :linea_credito, placeholder: "Linea de Credito del Cliente"%>
<% end %>
<%= f.submit 'Guardar'%>
<% end %>
</div>
param is missing or the value is empty: personas_x_tipos_persona
The problem is with this line #personas_x_tipos_personas = Persona.new(tipos_personas_params)(actually this is not needed) which is calling tipos_personas_params.
From the docs of require(key),
When passed a single key, if it exists and its associated value is
either present or the singleton false, returns said value
Otherwise raises ActionController::ParameterMissing
So, in your case the require is expecting :personas_x_tipos_persona, while this is missing in the params, so is the error.
Actually, the form object is :persona not :personas_x_tipos_persona. Also as I can see that you are using fields_for, so you need to whitelist :personas_x_tipos_persona_attributes inside persona_params and the tipos_personas_params method is not needed. The below code should get you going.
class PersonasController < ApplicationController
def create_cliente
#cliente = Persona.new(persona_params)
#this is not needed
##personas_x_tipos_personas = Persona.new(tipos_personas_params)
if #cliente.save
redirect_to show_clientes_path
else
render :new_cliente
end
end
private
def persona_params
params.require(:persona).permit(:nombre, :apellido, :direccion, :ruc, :contacto, :email, personas_x_tipos_persona_attributes: [:id, :linea_credito])
end
end
I have a double nested form:
<%= simple_form_for #item, html: { class: "create-item-form" } do |item_builder| %>
<div class="well">
<%= item_builder.input :name, required: false, error: false, label: "item name" %>
<%= item_builder.input :description, as: :text, required: false, error: false, label: "How do users earn this item?" %>
<%= item_builder.input :tag_list, required: false, label: "Tags (these will help users find your item)" %>
<%= item_builder.simple_fields_for :user_items do |user_item_builder| %>
<%= user_item_builder.input :foo, as: :hidden, input_html: { value: "bar" } %>
<%= user_item_builder.simple_fields_for :user_item_images do |user_item_images_builder| %>
<%= user_item_images_builder.input :foo, as: :hidden, input_html: { value: "bar" } %>
<%= user_item_images_builder.input :picture, as: :file, required: false,
error: false, label: "Pictures of you earning this item",
input_html: { multiple: true,
name: "item[user_items_attributes][0][user_item_images_attributes][][picture]" } %>
<% end %>
<% end %>
</div>
<div class="clearfix">
<%= item_builder.submit 'Submit new item request', class: "btn btn-primary pull-right inherit-width" %>
</div>
<% end %>
When a user doesn't upload a file for the user_item_image I need to display an error message. I wrote a custom validation:
user_item_image.rb
class UserItemImage < ActiveRecord::Base
include PicturesHelper
attr_accessor :foo
mount_uploader :picture, PictureUploader
belongs_to :user_item
validate :picture_size
validate :has_picture
private
def has_picture
errors.add(:base, 'You must include at least one picture.') if picture.blank?
end
end
But I get the error message:
User items user item images base You must include at least one picture.
How can I rewrite the validation so that it doesn't show the attribute and only shows the message.
Why not use
validates :picture, presence: true
on your useritem model
I am using the carrierwave gem to upload images of movie listings. I have created a migration creating a image column to my listings database.
updated the Listing model.rb file
class Listing < ActiveRecord::Base
mount_uploader :image, ImageUploader
belongs_to :user
end
added the :html = > { multipart: true } command to my simple form
<div class="wizard-container">
<%= simple_form_for(#listing, url: new_user_registration_path, method: :get, :html => { multipart: true } ) do |f| %>
<div class="card wizard-card ct-wizard-orange" id="wizard">
<!-- You can switch "ct-wizard-orange" with one of the next bright colors: "ct-wizard-blue", "ct-wizard-green", "ct-wizard-orange", "ct-wizard-red" -->
<div class="wizard-header">
<h3>
<b>LIST</b> YOUR MOVIE <br>
<small>This information will let us know more about your movie</small>
</h3>
</div>
And the image field to my listing.html.erb file
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<%= f.file_field :image %><br>
</div>
</div>
but when i create a listing the folloeing information , appears in console
Started GET "/users/sign_up?utf8=%E2%9C%93&listing%5Btitle%5D=Top+Gun&listing%5Btime%5D=14.35&listing%5Bdate%5D=24%2F03%2F2016&listing%5Bseats%5D=5&listing%5Bvenue_name%5D=Preston+Library&listing%5Bimage%5D=IMG_0892.JPG&listing%5Bprice%5D=2.3&listing%5Blocation%5D=Preston+Town+Hall&listing%5Bother_info%5D=This+is+a+great+venue&listing%5Bprojector%5D=0&listing%5Bcables%5D=0&listing%5Blaptops%5D=0&listing%5Bseating%5D=0&listing%5Bblinds%5D=0&listing%5Binternet%5D=0&listing%5Blighting%5D=0&listing%5Bcamcorder%5D=0&listing%5Bcatering%5D=0&listing%5Btoilets%5D=0&listing%5Bfire%5D=0&listing%5Bfire%5D=1&commit=Create+Listing" for 127.0.0.1 at 2015-03-24 14:36:31 +0000
Processing by Devise::RegistrationsController#new as HTML
Parameters: {"utf8"=>"✓", "listing"=>{"title"=>"Top Gun", "time"=>"14.35", "date"=>"24/03/2016", "seats"=>"5", "venue_name"=>"Preston Library", **"image"=>"IMG_0892.JPG",** "price"=>"2.3", "location"=>"Preston Town Hall", "other_info"=>"This is a great venue", "projector"=>"0", "cables"=>"0", "laptops"=>"0", "seating"=>"0", "blinds"=>"0", "internet"=>"0", "lighting"=>"0", "camcorder"=>"0", "catering"=>"0", "toilets"=>"0", "fire"=>"1"}, "commit"=>"Create Listing"}
So it captures the image but does mot display the image?
this app is slightly different to what i normally do , I make the user sign in first and then create details ,this app you create listings and then create an account
new.html.erb
<%= render 'layouts/header' %>
<h2 class="text-center">Sign up</h2>
<%
if !user_signed_in?
resource.listings.build
resource.listings[0].title = params[:listing][:title]
resource.listings[0].time = params[:listing][:time]
resource.listings[0].date = params[:listing][:date]
resource.listings[0].seats = params[:listing][:seats]
resource.listings[0].venue_name = params[:listing][:venue_name]
resource.listings[0].location = params[:listing][:location]
resource.listings[0].other_info = params[:listing][:other_info]
resource.listings[0].price = params[:listing][:price]
resource.listings[0].projector = params[:listing][:projector]
resource.listings[0].cables = params[:listing][:cables]
resource.listings[0].laptops = params[:listing][:laptops]
resource.listings[0].seating = params[:listing][:seating]
resource.listings[0].blinds = params[:listing][:blinds]
resource.listings[0].lighting = params[:listing][:lighting]
resource.listings[0].camcorder = params[:listing][:camcorder]
resource.listings[0].catering = params[:listing][:catering]
resource.listings[0].toilets = params[:listing][:toilets]
resource.listings[0].fire = params[:listing][:fire]
resource.listings[0].internet = params[:listing][:internet]
end
%>
<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name), html: {class: "form-signin"}) do |f| %>
<%= f.error_notification %>
<%= f.input :name, required: true, autofocus: true, label: false, placeholder: "Name", input_html: {class: "form-control"} %>
<%= f.input :email, required: true, label: false, placeholder: "Email", input_html: {class: "form-control"} %>
<%= f.input :password, required: true, label: false, placeholder: "Password", input_html: {class: "form-control"} %>
<%= f.input :password_confirmation, required: true, label: false, placeholder: "Password Confirmation", input_html: {class: "form-control"} %>
<div style="display:none">
<%= f.fields_for :listings do |listing_form| %>
<%= listing_form.input :title, label: false, placeholder: "Movie Title", input_html: {class: "form-control"} %>
<%= listing_form.input :time, label: false, placeholder: "What time does your movie start?", input_html: {class: "form-control"} %>
<%= listing_form.input :date, label: false, placeholder: "What date", input_html: {class: "form-control"} %>
<%= listing_form.input :seats, label: false, placeholder: "Number of seats", input_html: {class: "form-control"} %>
<%= listing_form.input :venue_name, label: false, placeholder: "Name of venue", input_html: {class: "form-control"} %>
<%= listing_form.input :location, label: false, placeholder: "Address", input_html: {class: "form-control", rows: 5 } %>
<%= listing_form.input :other_info, label: false, placeholder: "Other information", input_html: {class: "form-control", rows: 5} %>
<%= listing_form.input :price, label: false, placeholder: "Ticket Price (£)", input_html: {class: "form-control"} %>
<p> Projector </p>
<%= listing_form.input :projector, required: false, label: false %>
<p> Cable </p>
<%= listing_form.input :cables, required: false, label: false %>
<p> Laptop </p>
<%= listing_form.input :laptops, required: false, label: false %>
<p> Seating </p>
<%= listing_form.input :seating, required: false, label: false %>
<p> Blinds </p>
<%= listing_form.input :blinds, required: false, label: false %>
<p> Lighting </p>
<%= listing_form.input :lighting, required: false, label: false %>
<p> Camcorder </p>
<%= listing_form.input :camcorder, required: false, label: false %>
<p> Catering </p>
<%= listing_form.input :catering, required: false, label: false %>
<p> Toilets </p>
<%= listing_form.input :toilets, required: false, label: false %>
<p> Fire alarm </p>
<%= listing_form.input :fire, required: false, label: false %>
<p> Wifi/internet </p>
<%= listing_form.input :internet, required: false, label: false %>
<% end %>
</div>
<%= f.button :submit, "Sign up", class: "btn btn-primary btn-block" %>
<%= render "devise/shared/links" %>
<% end %>
application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) do |u|
u.permit(
:name,
:email, :password, :confirmation_password,
listings_attributes: [
:title, :time, :date, :seats,
:venue_name, :location, :other_info,
:price, :projector, :cables,
:laptops, :seating, :blinds,
:lighting, :camcorder, :catering,
:toilets, :fire, :internet, :image
]
)
end
devise_parameter_sanitizer.for(:account_update) << :name
end
end
any thoughts
Neil
rake routes
Rails.application.routes.draw do
resources :listings
devise_for :users
root 'pages#home'
get 'about' => 'pages#about'
get 'pages/contact'
get 'dashboard' => 'pages#dashboard'
get 'start' => 'listings#listing'