Simple Form and routing errors - ruby-on-rails

View/Form
<div class="col-lg-12">
<div class="ibox-content">
<div class="row">
<%= simple_form_for supplier_fuel_prices_path(#supplier,#fuel_price), method: :post do |f| %>
<%= f.input :regular, label: "Regular" %>
<%= f.input :medium, label: "Medium"%>
<%= f.input :premium, label: "Premium" %>
<%= f.input :diesel, label: "Diesel" %>
<%= f.button :submit, "Update"%>
<%end%>
</div>
</div>
</div>
</div>
</div>
controller
class Supplier::FuelPricesController < Supplier::ApplicationController
before_action :set_supplier
def index
end
def new
#fuel_price = #supplier.fuel_prices.build
end
def create
#fuel_price = #supplier.fuel_price.build(fuel_price_params)
if #fuel_price.save
flash[:notice] = "You have successfully Added new Fuel Price."
redirect_to supplier_fuel_prices_path
else
flash.now[:alert] = "Something went wrong. Please try again."
render "new"
end
end
private
def fuel_price_params
params.require(:fuel_price).permit(:regular, :medium, :premium, :diesel)
end
def set_supplier
#supplier = User.find_by(params[:supplier_id])
end
end
Models
User model has has_many :fuel_prices, foreign_key: :supplier_id
Fuel Price Model has belongs_to "supplier", class_name: "User"
Error i am getting when submitting the form is
No route matches [POST] "/supplier/fuel_prices/new"
My routes looks like this
namespace :supplier do
root to: 'dashboard#index', as: 'dashboard'
resources :retailers
resources :fuel_prices
end
Routes
supplier_fuel_prices_path GET /supplier/fuel_prices(.:format)
POST /supplier/fuel_prices(.:format) supplier/fuel_prices#create
new_supplier_fuel_price_path GET /supplier/fuel_prices/new(.:format) supplier/fuel_prices#new
edit_supplier_fuel_price_path GET /supplier/fuel_prices/:id/edit(.:format) supplier/fuel_prices#edit
supplier_fuel_price_path

You're just trying to post to the wrong path. A url ending in new is typically going to be a get request. Run rake routes and make sure you're posting to the correct post route and update your form.

Related

Simple form for not working on belongs to

Hello I have a simple rails app that has two models a goal and a task
The goal has many tasks, and a task belongs to a goal.
For some reason, probably a rookie error, I cannot get the form to the task form to render with simple form.
Models
Goal
class Goal < ApplicationRecord
has_many :tasks
end
Task
class Task < ApplicationRecord
belongs_to :goal
end
Controllers
Goals
class GoalsController < ApplicationController
before_action :set_goal, only: [:show]
def show
end
private
def set_goal
#goal = Goal.find(params[:id])
end
end
View views/goals/show
<div class="row">
<%= #goal.title %>
<div class="row">
<ul>
<% #goal.tasks.each do |task| %>
<li><%= task.name %></li>
<% end %>
</ul>
<%= render partial: 'tasks/form', locals: {comment: #goal.tasks.new} %>
</div>
Form views/tasks/_form
<%= simple_form_for([#goal, #task]) do |f| %>
<div class="form-inputs">
<%= f.input :name %>
<%= f.input :description %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
I get the error NoMethodError in Goals#show
so obviously I need to add the #task to my goals show.... but how
so I added to my goals show method
#task = Task.find_or_create_by(:task_id)
then i get the error
Unsupported argument type: task_id (Symbol)
so I added the following to my goals_controller
def show
#task = Goal.task.find_or_create_by(:task_id)
end
but then I get
NoMethodError in GoalsController#show
undefined method `task' for #<Class:0x00007ff8c79b0920> Did you mean? take
Routes
Rails.application.routes.draw do
resources :tasks
resources :goals
end
As per Jagdeep's comment above adding Try adding #task = #goal.tasks.build in goals_controller#show fixed this issue.
hope this helps

Values are nil for form submission (param is missing or the value is empty: amount)

I am a newbie with rails so forgive me. I know I am getting this error because I specified that amount be required for the parameters. If I did not, I end up with a transaction entry with just a transaction_id with every other field being nil. I believe my problem has to deal with my routes, but I'm not sure whats wrong.
My error:
ActionController::ParameterMissing in TransactionsController#create
param is missing or the value is empty: amount
But I can see that the fields are being passed:
Parameters:
{"utf8"=>"✓","authenticity_token"=>
"H+Xxpze7HWC9oduZC2CSxnWHztfhabEMRCoYy0Gw7upNknF2aIHsZ1G/xQOsICTVd7n4btqtT5760UL7QovIrA==",
"transaction"=>{"amount"=>"29", "transactionType"=>"withdraw"}, "commit"=>"Create Transaction"}
My TransactionsController:
class TransactionsController < ApplicationController
def new
#account = Account.find(params[:account_id])
#transaction = Transaction.new
#transaction.account_id = #account.id
end
def create
#transaction = Transaction.new(transactions_params)
if #transaction.save
redirect_to '/viewAccount/:id'
else
render 'new'
end
end
private
def transactions_params
params.require(:amount).permit(:account_id, :transactionType)
end
end
My New View (form):
<div class="destination">
<div class="container">
<div class = "form">
<h3>Add a new transaction for <%= current_user.email %> </h3>
<%= form_for(#transaction) do |f| %>
<%= f.text_field :amount %>
<%= f.select :transactionType, [['withdraw', 'withdraw'], ['deposit', 'deposit']] %>
<%= f.submit "Create Transaction", class: "btn-submit" %>
<% end %>
</div>
</div>
</div>
My routes:
Rails.application.routes.draw do
root 'mysite#index'
get 'signup' => 'users#new'
post 'signup' => 'users#create'
resources :users
get 'login' => 'sessions#new'
post 'login' => 'sessions#create'
get'newAccount' => 'accounts#new'
get 'viewAccount/:id' => 'banksite#show'
delete 'logout' => 'sessions#destroy'
get 'transactions' => 'transactions#new'
post 'transactions' => "transactions#create"
resources :transactions
Banking View/start of transactions new
<div class=content>
<div class=main>
<h1>Welcome to Online Banking <%= current_user.email %></h1>
<p>You're only allowed to see this page if you are logged in</p>
<h2><%= current_user.email %> 's Account Summary</h2>
<h3>Balance: $ <%= #account.balance %> </h3>
<%= link_to "Create Transaction",
:controller => "transactions",
:action => "new",
:account_id => #account.id %>
</div>
</div>
</div>
My models:
class User < ActiveRecord::Base
has_secure_password
has_one :account
end
class Account < ActiveRecord::Base
belongs_to :user
has_many :transactions
end
class Transaction < ActiveRecord::Base
belongs_to :account
end
I would appreciate any insight into this error.
This:
params.require(:amount).permit(:account_id, :transactionType)
is expecting parameters like:
"amount" => { "account_id" => "...", "transactionType" => "..." }
but your parameters look like:
"transaction"=>{"amount"=>"29", "transactionType"=>"withdraw"}
Also, there is no account_id in your form.
First you'll need to get account_id into your form with something like:
<%= f.hidden_field :account_id %>
Then you need to update your form parsing in your controller with something like:
params.require(:transaction).permit(:account_id, :amount, :transactionType)
so that it will be looking for "transaction" at the top level and "account_id", "amount", and "transactionType" inside that.

Simple form not submitting to database

I'm building a simple online shop for practice and want to track order histories, at the moment I'm getting the user to submit but the shipping address and order history, later I'll upgrade order history to be a hidden field.
The problem is that I can't get the simple form to submit anything to my database.
My form looks like this:
<p class="text-center">
congratulations your order is almost complete, please fill out the form below to place your order or <%= link_to "browse other products.", root_path %>
</p>
<%= simple_form_for #placeorder, html: { multipart: true } do |f| %>
<%= f.error_notification %>
<div class="form-inputs" >
<%= f.input :shipping_address, label: false, placeholder: 'Shipping address', input_html: { class: 'input-lg', required: true } %>
<%= f.input :order_history, label: false, placeholder: 'order_history', input_html: { class: 'input-lg', required: true } %>
</div>
<div class="form-actions">
<%= f.button :submit, "Confirm order" %>
</div>
<% end %>
My place order controller looks like this:
class PlaceOrdersController < ApplicationController
def new
current_order.order_items.each do |order_item|
#last_item_name = order_item.product.name
end
#placeorder = PlaceOrder.new
#order = current_order.order_items
end
def create
#placeorder = PlaceOrder.create(place_order_params)
p "HELLO #{#placeorder}"
if #placeorder.save
flash[:success] = "You've made your order"
redirect_to root_path
else
flash[:alert] = "Something went wrong, check the form and submit your order again"
render :new
end
end
private
def place_order_params
params.require(:place_order).permit(:shipping_address, :order_history)
end
end
My routes.rb looks like this:
Rails.application.routes.draw do
resources :products
resources :checkout
resources :place_orders
resource :cart, only: [:show]
resources :order_items, only: [:create, :update, :destroy], defaults: { format: 'js' }
root to: "products#index"
devise_for :users, :controllers => { registrations: 'registrations' }
end
I have other forms that are working fine and they look the same. Any help would be greatly appreciated.

Route issues while using nested_attributes in Rails 4

I want to use a single form to send data to two tables: Questions and Answers.
To do so, I am using accepts_nested_attributes_for as outlined here. Here is my Question.rb model:
class Question < ActiveRecord::Base
has_many :answers
belongs_to :category
accepts_nested_attributes_for :answers, :allow_destroy => true
end
Then in my _form view, I am using:
<% form_for(#question, :url => question_path(#question)) do |f| %>
<% f.text_field :question_text %>
<% f.fields_for :answers do |builder| %>
<%= builder.text_field :answer_text %>
<% end %>
<% end %>
This produces a confusing error: No route matches {:action=>"show", :controller=>"questions", :id=>nil} missing required keys: [:id].
Even if I manually append an id onto the params (like http://localhost:3000/triviabuilder/new?id=1), I still receive this error.
Do I really need to specify an ID in the params, and if so, should that be done in the controller?
EDIT - Adding Routes.rb
Example::Application.routes.draw do
resources :games
resources :questions
resources :answers
resources :triviabuilder
devise_for :users
root "pages#home"
get "triviabuilder" => "triviabuilder#index"
get "new_triviabuilder" =>"triviabuilder#new"
EDIT 2 - Adding TriviaBuilder Controller
Tries to call the Question table since it includes nested_attributes
class TriviabuilderController < ApplicationController
def new
#question = Question.new
end
def create
#question = question.new(params[:question])
if #question.save
redirect_to triviabuilder_path, :notice => "Your post was saved"
else
render "new"
end
end
end
This is producing a "show" error for No route matches {:action=>"show", :controller=>"triviabuilder"} missing required keys: [:id].
Try changing following things
routes.rb
resources :triviabuilders
_form.html.erb
<%= form_for(Question.new , url: triviabuilders_path) do |f| %>
<% f.text_field :question_text %>
<% f.fields_for :answers do |builder| %>
<%= builder.text_field :answer_text %>
<% end %>
<% end %>
Controller name should be plural, change to TriviabuildersController from TriviabuilderController.
create action should be as follows:
def create
#question = Question.new(params[:question])
if #question.save
redirect_to triviabuilders_path, :notice => "Your post was saved"
else
render "new"
end
end
Remove the following line of code from form_for
:url => question_path(#question)
Also, you need to add = to your form_for tag otherwise it won't be visible, Your form_for should look like this
<%= form_for #question do |f| %>
Rails will automatically map it to the update action.
Hope that helps!

ActionController::RoutingError: No route matches [POST] "/locations/new"

Routes
resources :locations, :only => [:new, :create]
Controller
class LocationsController < ApplicationController
def new
#location = Location.new
end
def create
#location = Location.new(location_params)
if #location.save
flash[:notice] = 'Created location successfully'
redirect_to new_location_path
else
flash[:notice] = 'Invalid information. Please try again'
render :new
end
end
private
def location_params
params.require(:location).permit(:name, :street, :city, :state)
end
end
Error message when I click save.
ActionController::RoutingError:
No route matches [POST] "/locations/new"
view
<%= simple_form_for :locations do |form| %>
<%= form.input :name %>
<%= form.input :street %>
<%= form.input :city %>
<%= form.input :state %>
<%= form.submit 'Create location' %>
<% end %>
Using capybara to test that when I click on save it creates a new location. I'm not quite sure why it doesn't know what the post route is because I have the new and create routes. If I put a binding.pry right underneath the create method it doesn't get called. So my create method is not being called for some reason.
EDIT:
Rake Routes
locations POST /locations(.:format) locations#
new_location GET /locations/new(.:format) locations#new
A resource normally GETs to new and POSTs to create. So your form is probably submitting back to the new actions instead of submitting to the create action.
Here's the guide for this: http://guides.rubyonrails.org/routing.html#crud-verbs-and-actions
The problem was in the views.
<%= simple_form_for :locations do |form| %>
<%= form.input :name %>
<%= form.input :street %>
<%= form.input :city %>
<%= form.input :state %>
<%= form.submit 'Create location' %>
<% end %>
I was calling on locations symbol when I should have been calling on the instance variable #location from the controller.
The actual problem was that rails 3.2.12 doesn't take private params
Using resources, the new action should be fetched with GET instead of POST. create will be POST. Check your rake routes

Resources