Ruby on Rails: Saving form check boxes to Boolean in Postgres - ruby-on-rails

Rails noob here, how do I get a Rails form to save a boolean checkbox to postgres? I've tried dozens of things I've found online and none of it is working. No matter what I do, the entry in the Postgres DB is "Null". Here is my
Model(schema):
ActiveRecord::Schema.define(version: 20171227200151) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "notes", force: :cascade do |t|
t.string "note_title"
t.string "note_text"
t.boolean "note_scratch", default: false, null: false
t.boolean "note_info"
t.boolean "note_reminder"
t.boolean "note_task"
t.string "note_tags"
t.date "note_remind_date"
t.time "note_remind_time"
t.integer "note_archived"
t.date "note_archived_date"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
view:
<%= form_with scope: :note, url: notes_path, local: true do |f| %>
<p>
<%= f.label :note_title %><br>
<%= f.text_field :note_title %>
</p>
<p>
<%= f.label :note_text %><br>
<%= f.text_area :note_text %>
</p>
<p>
<%= f.label :notes_scratch, "Scratch" %>
<%= f.check_box :notes_scratch %>
<%= f.label :notes_info, "Info" %>
<%= f.check_box :notes_info %>
<%= f.label :notes_reminder, "Reminder" %>
<%= f.check_box :notes_reminder %>
<%= f.label :notes_task, "Task" %>
<%= f.check_box :notes_task %>
</p>
<p>
<%= f.label :note_tags %><br>
<%= f.text_field :note_tags %>
</p>
<p>
<%= f.label :note_remind_date %><br>
<%= f.date_field :note_remind_date %>
</p>
<p>
<%= f.label :note_remind_time %><br>
<%= f.time_field :note_remind_time %>
</p>
<%= f.submit %>
<% end %>
Controller:
class NotesController < ApplicationController
def new
end
def create
# for testing
# render plain: params[:note].inspect
#note = Note.new(note_params)
#note.save
redirect_to #note
end
private
def note_params
params.require(:note).permit(:note_title, :note_text, :note_scratch, :note_info, :note_reminder, :note_task, :note_tags, :note_remind_date, :note_remind_time, :note_archived, :note_archived_date)
end
end
If I just render the form results, it will show checked boxes as 1s, but it always comes up Null in the database, even if I set the datatype to Integer (hoping it would store the 1). All of the other fields record just fine. It's only the checkboxes that don't work.
I appreciate any assistance you can lend!
-Brick

Review your note_params (and schema.rb):
def note_params
params.require(:note).permit(:note_title, :note_text, :note_scratch, :note_info, :note_reminder, :note_task, :note_tags, :note_remind_date, :note_remind_time, :note_archived, :note_archived_date)
end
In your view: notes_* needs to be singular as your schema is note_*.

Related

Using a Hidden Field inside a Rails 5 Partial to Save an Array

I am trying to do the seemingly innocuous task of passing an array of tags to a new subscriber form, based on which page it's rendered on.
My Subscriber table looks like this in schema.rb:
create_table "subscribers", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.string "phone"
t.string "email"
t.text "tags", default: [], array: true
t.text "admin_notes"
t.boolean "unsubscribe"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
My partial is rendered like this:
<%= render partial: "layouts/new_subscriber", locals: { tags: "buyer, LM-house-tour-checklist" } %>
Which brings up this _new_subscriber.html.erb partial:
<%= simple_form_for(#new_subscriber) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.label :first_name %>
<%= f.text_field :first_name, required: true, class: "form-control" %>
<%= f.label :last_name %>
<%= f.text_field :last_name, required: true, class: "form-control" %>
<%= f.label :phone %>
<%= f.text_field :phone, required: true, class: "form-control" %>
<%= f.label :email %>
<%= f.text_field :email, required: true, class: "form-control" %>
<%= f.hidden_field :tags, value: tags %>
</div>
<div class="form-actions text-center">
<%= f.submit "Get My Checklist", class: "btn" %>
</div>
<% end %>
I have tested using the Chrome code inspector that "buyer, LM-house-tour-checklist" is getting passed into the hidden field value.
However, when I submit, it creates the subscriber with a :tags attribute of ["uyer"]. This is super weird and unexplainable to me.
Some other info:
There is nothing in my subscriber model.
#new_subscriber is defined in my ApplicationController using before_action :new_subscriber and def new_subscriber #new_subscriber = Subscriber.new end
I have tried the method described here, but to no avail
Can anyone help me do this in the "Railsiest" way possible? It dosn't seem like that unusual of an ask, but I can't get it to work properly.
Maybe because it's sent as string.
Try to add attr_accessor :plain_tags in model
Instead of tags field use this attribute.
And in before_create callback write something like
before_create :populate_tags
def populate_tags
return if self.tags_plain.blank?
self.tags = self.tags_plain.split(",")
end

Rails: param is missing or the value is empty: stock

I keep getting an error when i try to create a new item for a database that displays ActionController::ParameterMissing in StocksController#create
param is missing or the value is empty: stock.
It says the source is at
private
def stock_params
params.require(:stock).permit(:product_name, :brand_name, :item_id, :upc_code, :color, :department, :size, :condition, :fabric_type, :shipping_weight, :sku, :asin, :quantity, :cost_price, :sell_price, :key_product_features, :product_description, :search_terms, :status, :listing_in_usa, :listing_in_canada, :listing_in_mexico)
end
Under my stockscontroller file on the terminal it says:
Started POST "/stocks" for 107.15.253.59 at 2017-05-22 16:38:14 +0000
Cannot render console from 107.15.253.59! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by StocksController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"poJrp+PWBi7bxgeauJ37VNh/Shyk0q6iCNA+5Y4UBIZ/rf5dXYVBOgtPpVPUbfzjLsn9Kcz/Fn6kHKXHG0dUuQ==", "stocks"=>{"product_name"=>"", "brand_name"=>"", "item_id"=>"", "upc_code"=>"", "color"=>"", "department"=>"", "size"=>"", "condition"=>"", "fabric_type"=>"", "shipping_weight"=>"", "sku"=>"", "asin"=>"", "quantity"=>"", "cost_price"=>"", "sell_price"=>"", "key_product_feature"=>"", "product_description"=>"", "search_terms"=>"", "status"=>"", "listing_in_usa"=>"", "listing_in_canada"=>"", "listing_in_mexico"=>""}, "commit"=>"Save Stocks"}
Completed 400 Bad Request in 1ms (ActiveRecord: 0.0ms)
ActionController::ParameterMissing (param is missing or the value is empty: stock):
app/controllers/stocks_controller.rb:48:in `stock_params'
app/controllers/stocks_controller.rb:15:in `create'
I basically repeated a code that is similar to this that works that i already created, but i can't find why this is wrong. I have 2 types of databases, Vendors and Stocks, but the Stocks database isn't working.
This is the code for stockscontroller/concerns/controllers/apps
class StocksController < ApplicationController
def show
#stock = Stock.find(params[:id])
end
def index
#stocks = Stock.all
end
def new
#stock = Stock.new
end
def create
#stock = Stock.new(stock_params)
if #stock.save
redirect_to #stock
else
render 'new'
end
end
def edit
#stock = Stock.find(params[:id])
end
def update
#stock = Stock.find(params[:id])
if #stock.update(stock_params)
redirect_to #stock
else
render 'edit'
end
end
def destroy
#stock = Stock.find(params[:id])
#stock.destroy
redirect_to stock_path
end
end
private
def stock_params
params.require(:stock).permit(:product_name, :brand_name, :item_id, :upc_code, :color, :department, :size, :condition, :fabric_type, :shipping_weight, :sku, :asin, :quantity, :cost_price, :sell_price, :key_product_features, :product_description, :search_terms, :status, :listing_in_usa, :listing_in_canada, :listing_in_mexico)
end
code for new/stocks/views/apps
<body>
<div class = "head5">
<h1>New Inventory</h1>
<div class = "header5">
<h3> Apparel Inventory</h3>
</div>
</div>
</body>
<%= form_for :stocks, url: stocks_path do |f| %>
<p>
<%= f.label :product_name %><br>
<%= f.text_field :product_name %>
</p>
<p>
<%= f.label :brand_name %><br>
<%= f.text_field :brand_name %>
</p>
<p>
<%= f.label :item_id %><br>
<%= f.text_field :item_id %>
</p>
<p>
<%= f.label :upc_code %><br>
<%= f.text_field :upc_code %>
</p>
<p>
<%= f.label :color %><br>
<%= f.text_field :color %>
</p>
<p>
<%= f.label :department %><br>
<%= f.text_field :department %>
</p>
<p>
<%= f.label :size %><br>
<%= f.text_field :size %>
</p>
<p>
<%= f.label :condition %><br>
<%= f.text_field :condition %>
</p>
<p>
<%= f.label :fabric_type %><br>
<%= f.text_field :fabric_type %>
</p>
<p>
<%= f.label :shipping_weight %><br>
<%= f.text_field :shipping_weight %>
</p>
<p>
<%= f.label :sku %><br>
<%= f.text_field :sku %>
</p>
<p>
<%= f.label :asin %><br>
<%= f.text_field :asin %>
</p>
<p>
<%= f.label :quantity %><br>
<%= f.text_field :quantity %>
</p>
<p>
<%= f.label :cost_price %><br>
<%= f.text_field :cost_price %>
</p>
<p>
<%= f.label :sell_price %><br>
<%= f.text_field :sell_price %>
</p>
<p>
<%= f.label :key_product_feature %><br>
<%= f.text_field :key_product_feature %>
</p>
<p>
<%= f.label :product_description %><br>
<%= f.text_field :product_description %>
</p>
<p>
<%= f.label :search_terms %><br>
<%= f.text_field :search_terms %>
</p>
<p>
<%= f.label :status %><br>
<%= f.text_field :status %>
</p>
<p>
<%= f.label :listing_in_usa %><br>
<%= f.text_field :listing_in_usa %>
</p>
<p>
<%= f.label :listing_in_canada %><br>
<%= f.text_field :listing_in_canada %>
</p>
<p>
<%= f.label :listing_in_mexico %><br>
<%= f.text_field :listing_in_mexico %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
<%= link_to 'Back', stocks_path %>
Code for the model
class Stock < ApplicationRecord
end
my routes/locals/config/app file
Rails.application.routes.draw do
get 'welcome/index'
resources :vendors
resources :stocks
root 'welcome#index'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
my schema/migrate/db/config/apps
ActiveRecord::Schema.define(version: 20170522154349) do
create_table "stocks", force: :cascade do |t|
t.string "product_name"
t.string "brand_name"
t.integer "item_id"
t.integer "upc_code"
t.string "color"
t.string "size"
t.string "department"
t.string "condition"
t.string "fabric_type"
t.string "shipping_weight"
t.string "sku"
t.string "asin"
t.integer "quantity"
t.string "cost_price"
t.string "sell_price"
t.string "key_product_feature"
t.text "product_description"
t.text "search_terms"
t.string "status"
t.string "listing_in_usa"
t.string "listing_in_canada"
t.string "listing_in_mexico"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "vendors", force: :cascade do |t|
t.string "company"
t.string "contact_name"
t.string "phone"
t.string "email"
t.string "moq"
t.string "cost_per_item"
t.string "payment_method"
t.string "terms"
t.string "turnover"
t.string "returns"
t.text "notes"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
The new error says:
ActiveRecord::RecordNotFound in StocksController#show
Couldn't find Stock with 'id'=5
At the source on app/controllers/stocks_controller.rb:
class StocksController < ApplicationController
def show
#stock = Stock.find(params[:id])
end
def index
With the terminal saying:
ActiveRecord::RecordNotFound (Couldn't find Stock with 'id'=5):
app/controllers/stocks_controller.rb:3:in `show'
You're not returning a :stock key in your params.
Change
<%= form_for :stocks, url: stocks_path do |f| %>
Into
<%= form_for :stock, url: stocks_path do |f| %>
This seems to be a plural vs. sigular issue.
Your code is requiring a stock param, but it's getting stocks.
Try changing this line:
<%= form_for :stocks, url: stocks_path do |f| %>
to
<%= form_for :stock, url: stocks_path do |f| %>

param is missing or the value is empty: item in ruby on rails on windows

I've looked stackoverflow questions regarding to this question(also followed all the instructions given). I am trying to add an new item but I am encountering this error..
Question: Why I am getting this error? What is it?
Controller
class ItemsController < ApplicationController
def index
end
def addItem
end
def create
#item = Item.new(post_params)
#item.save
redirect_to #item
end
def show
#item = Item.find(params[:id])
end
private
def post_params
params.require(:item).permit(:item, :description, :price)
end
end
Add Item view
<%= form_for :post, url: items_create_path do |f| %>
<p>
<%= f.label :Item %><br>
<%= f.text_field :item %>
</p>
<p>
<%= f.label :Description %><br>
<%= f.text_area :description %>
</p>
<p>
<%= f.label :Price %><br>
<%= f.text_field :price %>
</p>
<p>
<%= f.submit :Submit %>
</p>
<% end %>
<%= link_to 'BACK', items_path %>
Routes
Rails.application.routes.draw do
# URL Controller#method
get '/items/addItem' => 'items#addItem'
get '/items/' => 'items#index'
post '/items/create' => 'items#create'
end
My Table
ActiveRecord::Schema.define(version: 20170323165252) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "items", force: :cascade do |t|
t.string "name"
t.text "description"
t.integer "price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
Your items table does not have item field. You are using the name item for name field. So replace item with name and it should work.
Controller
params.require(:item).permit(:name, :description, :price)
Add Item view
<p>
<%= f.label :Item %><br>
<%= f.text_field :name %>
</p>

Choose right method in Controller according to the forms - Rails 5

I have two models: Entreprise & Prospect
create_table "entreprises", force: :cascade do |t|
t.string "name"
t.text "adresse"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "siret"
t.string "numtva"
t.string "tel"
t.integer "prospect_id"
end
create_table "prospects", force: :cascade do |t|
t.string "full_name"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "entreprise_id"
end
Prospects belongs_to entreprises, and Entreprise has_many Prospects.
-
My issue :
I have two buttons : Create a new entreprise or reate a new prospect.
I have two way to create a new prospect :
Under my entreprise because an entreprise has_many prospects
Directly from navbar with "create prospect" button
So I have two forms :
If we click on "create prospect" (create method in my controller):
<%= form_for :prospects, url: prospects_path do |f| %>
<p>
<%= f.label :entreprises %><br><br>
<%= f.collection_select :entreprise_id, Entreprise.order(:name),:id,:name, include_blank: true %>
</p><br>
<p>
<%= f.label :full_name %> <br>
<%= f.text_field :full_name %><br>
</p><br>
<p>
<%= f.label :email %> <br>
<%= f.text_field :email %><br>
</p><br>
<p>
<%= f.submit %>
</p>
<% end %>
If we create prospect under entreprise ("directcreate" method in my controller) :
<%= form_for([#entreprise, #entreprise.prospects.build]) do |f| %>
<p>
<%= f.label :full_name %> <br>
<%= f.text_field :full_name %><br>
</p><br>
<p>
<%= f.label :email %> <br>
<%= f.text_field :email %><br>
</p><br>
<p>
<%= f.submit %>
</p>
<% end %>
My Controller for Prospects :
class ProspectsController < ApplicationController
def index
#prospects = Prospect.all.limit(15).order('created_at DESC')
end
def new
#prospect = Prospect.new
end
def directcreate
#prospect = Prospect.new(entreprise_params)
if #prospect.save
redirect_to #prospect
else
render 'new'
end
end
def create
#entreprise = Entreprise.find(params[:entreprise_id])
#prospect = #entreprise.prospects.create(params[:prospect].permit(:full_name, :email))
redirect_to entreprise_path(#entreprise)
end
def destroy
#entreprise = Entreprise.find(params[:entreprise_id])
#prospect = #entreprise.prospects.find(params[:id])
#prospect.destroy
redirect_to entreprise_path(#entreprise)
end
end
My problème is that the "create" method in my controller is the only one who works.. and not "directcreate" method.
--
QUESTION : How can I do to choose the controller I want according to the form ?
My question is probably not well ask.
FYI I try this in my new.html.erb :
<%= render 'formdirect', :controller => "directcreate" %>
but it doesn't work.
You can try something like this. You just have to explicitly choose your controller action.
<%= form_for([#entreprise, #entreprise.prospects.build], :url => { :action => : directcreate }) do |f| %>
<p>
<%= f.label :full_name %> <br>
<%= f.text_field :full_name %><br>
</p><br>
<p>
<%= f.label :email %> <br>
<%= f.text_field :email %><br>
</p><br>
<p>
<%= f.submit %>
</p>
<% end %>

Rails grab input value on submit in controller

I have a customer model that belongs to user. However, when creating the new customer, the user will not be signed in. Instead I will be assigning the user based on his name attribute.
Here is the customer migration:
create_table :customers do |t|
t.belongs_to :user
t.string :name, null: false
t.date :install_date, null: false
t.decimal :mmr, null: false
t.boolean :sixty_month, default: false
t.boolean :eft, default: false
t.boolean :activation, default: false
t.timestamps
end
I then have a new customer form:
<h1>Create Customer</h1>
<%= form_for #customer do |f| %>
<div>
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<div>
<%= f.label :install_date %>
<%= f.date_field :install_date %>
</div>
<div>
<%= f.label :mmr %>
<%= f.number_field :mmr %>
</div>
<div>
<%= f.label :sixty_month %>
<%= f.check_box :sixty_month %>
</div>
<div>
<%= f.label :eft %>
<%= f.check_box :eft %>
</div>
<div>
<%= f.label :activation %>
<%= f.check_box :activation %>
</div>
<div>
<%= f.label :users_name %>
<%= f.text_field :users_name %>
</div>
<%= f.submit 'Create Customer' %>
<% end %>
I need to get the users_name field and match it with the associated user and take that users id and assign it to the customers :user_id attribute. In the customers controllers create action so far I have:
#customer.user_id = User.where("name = #{}").id
I need to pull to input from the users_name field in the new customer form and put it into the above code somehow. I just don't know how haha. All help is appreciated!
You will probably want to move this out of the controller and into a helper method but you could do like this:
def create
#customer = Customer.new(customer_params)
if params[:users_name]
user = User.find_by(name: params[:users_name])
#customer.user_id = user.id unless user.nil?
end
if #customer.save
flash[:success] = "Customer created!"
redirect_to #customer
else
render 'new'
end
end
This is assuming you are using Rails 4.

Resources