I am trying to implement a Parking Permit application page using ROR. I couldn't get my data saved into the database. The permit database is associated with the user also. The program won't save the data and execute the else statement. There is no error generated, i think i have missed something but i don't know the exact problem. Any help is appreciated!
Permit_controller.rb
class PermitsController < ApplicationController
before_action :set_permit, only: [:show, :destroy]
def index
#permits = Permit.all
end
def new
#permits = Permit.new
end
def create
#permits = Permit.new(permit_params)
if #permits.save
redirect_to root_path
else
redirect_to contact_path
end
end
def destroy
end
def show
#permits = Permit.find(params[:id])
end
private
# Use callbacks to share common setup or constraints between actions.
def set_permit
#permits = Permit.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def permit_params
params.require(:permit).permit(:vehicle_type, :name, :studentid, :department, :carplate,:permitstart, :permitend)
end
end
Permit.rb
class Permit < ApplicationRecord
belongs_to :user
end
Create_permit.rb
class CreatePermits < ActiveRecord::Migration[5.0]
def change
create_table :permits do |t|
t.string :vehicle_type
t.string :name
t.string :studentid
t.string :department
t.string :carplate
t.date :permitstart
t.date :permitend
t.references :user, foreign_key: true
t.timestamps
end
add_foreign_key :permits, :user
add_index :permits, [:user_id, :created_at]
end
end
User.rb
class User < ApplicationRecord
has_secure_password
has_many :permits
end
#book pg 264 Validation
permit/new.html.erb
<% provide(:title, 'New Permit') %>
<h1>Permit Application</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_for(#permits) do |f| %>
<%= f.label :"Vehicle" %>
<%= f.text_field :vehicle_type, class: 'form-control' %>
<%= f.label :"License Plate" %>
<%= f.text_field :carplate, class: 'form-control' %>
<%= f.label :"Student ID" %>
<%= f.text_field :studentid, class: 'form-control' %>
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
<%= f.label :"Department of applicant" %>
<%= f.text_field :department, class: 'form-control' %>
<%= f.label :permit_start %>
<%= f.date_select :permitstart, class: 'form-control' %>
<%= f.label :permit_end %>
<%= f.date_select :permitend, class: 'form-control' %>
<%= f.submit "Submit", class: "btn btn-primary" %>
<% end %>
</div>
</div>
schema.rb
ActiveRecord::Schema.define(version: 20160921071908) do
create_table "permits", force: :cascade do |t|
t.string "vehicle_type"
t.string "name"
t.string "studentid"
t.string "department"
t.string "carplate"
t.date "permitstart"
t.date "permitend"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["user_id"], name: "index_permits_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "name"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
t.integer "user_type"
end
end
check with this #permits.save!.
it shows the exact error.
module ApplicationHelper
#for current user to use through out the app
def current_user
#current_user ||= session[:current_user_id] && User.find_by_id(session[:current_user_id]) # Use find_by_id to get nil instead of an error if user doesn't exist
end
end
and
def create
#permits = Permit.new(permit_params)
#permits.user = current_user
if #permits.save
redirect_to root_path
else
redirect_to contact_path
end
end
test it
Or you can just say that a permit has a single user and avoid the confusion.
#models/permit.rb
class Permit < ApplicationRecord
has_one :user
end
#controllers/permit_controller.rb
def create
#user = User.find(session[:user_id]) #use your session variable
#permits = Permit.new(permit_params)
if #permits.save
#user.permits << #permits
redirect_to root_path
else
redirect_to contact_path
end
end
It will save permits for the logged in user.
Related
I am trying to print out a form using the simple_form gem but I am getting this error:
ActionController::ParameterMissing in HomepageController#newbands
param is missing or the value is empty: band
homepage_controller.rb
class HomepageController < ApplicationController
def index
end
def bands
end
def newbands
#band = Band.new
#band = Band.create(band_params)
if #band.save
redirect_to "/newbands"
else
render "/"
end
end
private
def band_params
params.require(:band).permit(:name, :country, :members, :genre)
end
end
newbands.html.erb
<%= simple_form_for #band do |b| %>
<%= b.input :name %>
<%= b.input :country %>
<%= b.input :members %>
<%= b.input :genre %>
<%= b.button :submit %>
<% end %>
schema.rb
ActiveRecord::Schema[7.0].define(version: 2022_03_14_133839) do
create_table "bands", force: :cascade do |t|
t.string "name"
t.string "country"
t.integer "members"
t.string "genre"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
I'm doing a parking permit website. The problem I met is that I'm not able to save my data to the PERMIT database which associated with the USER database. The problem i think is I didn't bring the user to the permit(Maybe i missed something). I found out the error when I trying to save from Permit.errors.full_messages is ["User must exist"]. Any help is appreciated, Thank you!
Schema.rb
ActiveRecord::Schema.define(version: 20160920143651) do
create_table "permits", force: :cascade do |t|
t.string "vehicle_type"
t.string "name"
t.string "studentid"
t.string "department"
t.string "carplate"
t.string "duration"
t.date "permitstart"
t.date "permitend"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["user_id"], name: "index_permits_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "name"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
t.integer "user_type"
end
end
Create_permit.rb
class CreatePermits < ActiveRecord::Migration[5.0]
def change
create_table :permits do |t|
t.string :vehicle_type
t.string :name
t.string :studentid
t.string :department
t.string :carplate
t.string :duration
t.date :permitstart
t.date :permitend
t.references :user, foreign_key: true
t.timestamps
end
add_index :permits, :user_id
end
end
Permit_controller
class PermitsController < ApplicationController
before_action :set_permit, only: [:show, :destroy]
def index
#permits = Permit.all
end
def new
#permits = Permit.new
end
def create
#permits = Permit.new(permit_params)
if #permits.save
redirect_to #permits
else
redirect_to contact_path
end
end
def destroy
Permit.destroy_all(user_id: 1)
respond_to do |format|
format.html { redirect_to users_url, notice: 'Permit was successfully canceled.' }
format.json { head :no_content }
end
end
def show
#permits = Permit.find(params[:id])
end
def update
respond_to do |format|
if #permits.update(user_params)
format.html { redirect_to #user, notice: 'Permit was successfully updated.' }
format.json { render :show, status: :ok, location: #user }
else
format.html { render :edit }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_permit
#permits = Permit.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def permit_params
params.require(:permit).permit(:vehicle_type, :name, :studentid, :department, :carplate, :duration, :permitstart, :permitend)
end
end
user.rb
class User < ApplicationRecord
has_many :permits
has_secure_password
end
Permit.rb
class Permit < ApplicationRecord
belongs_to :user
end
permit/new.html.erb
<% provide(:title, 'New Permit') %>
<h1>Permit Application</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_for(#permits) do |f| %>
<%= f.label :"Vehicle" %>
<%= f.text_field :vehicle_type, class: 'form-control' %>
<%= f.label :"License Plate" %>
<%= f.text_field :carplate, class: 'form-control' %>
<%= f.label :"Student ID" %>
<%= f.text_field :studentid, class: 'form-control' %>
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
<%= f.label :"Department of applicant" %>
<%= f.text_field :department, class: 'form-control' %>
<%= f.label :permit_start %>
<%= f.date_select :permitstart, class: 'form-control' %>
<%= f.label :permit_end %>
<%= f.date_select :permitend, class: 'form-control' %>
<%= f.submit "Submit", class: "btn btn-primary" %>
<% end %>
</div>
</div>
I guess you are using Rails 5. The problem is you have belongs_to association on permit that is belongs to user but while creating permit you are not associating any user with it and in Rails 5 it is mandatory to assign data to belongs_to association i.e you can not save permit when it don't have user_id so try to assign a user_id to permit. refer this for change to rails 5 belongs_to association
Where exactly is your error ? If in update action, you have to change your before_action. You must add there :update action.
before_action :set_permit, only: [:show, :destroy, :update]
I currently have an attribute on Subscriber called mug_number its data type is an integer. I have a page where a person can sign up to be a Subscriber, Whenever a person signs up I want this number to increment by 1 so that in the index I can see what number belongs to each person. I'll post code for clarity.
SUBSCRIBER CONTROLLER:
class SubscribersController < ApplicationController
helper_method :sort_column, :sort_direction
def index
#search = Subscriber.search(params[:q])
#subscriber = #search.result
#search.build_condition if #search.conditions.empty?
#search.build_sort if #search.sorts.empty?
end
def new
#subscriber = Subscriber.new
end
def create
#subscriber = Subscriber.create(subscriber_params)
if #subscriber.save
flash[:notice] = "Subscriber Has Been Successfully Created"
redirect_to new_subscriber_path(:subscriber)
else
render "new"
end
end
SCHEMA:
create_table "subscribers", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.string "email"
t.string "phone_number"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "visit"
t.integer "mug_number"
end
As you can see in the schema I have the mug_number attribute on Subscriber
Right now I'm trying to add a hidden_field for the form but I don't think that the right implementation?
FORM:
<%= form_for #subscriber do |form| %>
<div class="form-group">
<p>
<%= form.text_field :first_name, placeholder: "First Name", class: "text_field" %>
</p>
<p>
<%= form.text_field :last_name, placeholder: "Last Name", class: "text_field" %>
</p>
<p>
<%= form.text_field :phone_number, placeholder: "phone", class: "text_field" %>
</p>
<p>
<%= form.text_field :email, placeholder: "Email", class: "text_field" %>
</p>
<%= form.hidden_field :mug_number %>
</div>
<%= form.submit "Sign Up", class: "btn" %>
<% end %>
This should be an easy story but for some reason I can't seem to figure it out? Any help would be great!
You shouldn't need a hidden field because you don't want to generate the number until it's time to save the record.
A before_create callback on the Subscriber model should do.
class Subscriber < ActiveRecord::Base
before_create :generate_mug_number
private
def generate_mug_number
last_number = Subscriber.maximum(:mug_number) || 0
self.mug_number = last_number + 1
end
end
I have a form that collects company information as well as the first user (the company admin). When I submit the form, the company attributes are saved to the db. However, the user attributes are not. I get the error Unpermitted parameters: user. I can't figure out why the user is not being created and saved.
I have:
class CompaniesController < ApplicationController
def new
#company = Company.new
#plans = Plan.all
end
def create
#company = Company.new(company_params)
#user = User.new
#user.role = "admin"
#user.save
if #company.save
redirect_to #company, notice: 'Company was successfully created.'
else
render action: 'new'
end
end
private
# Never trust parameters from the scary internet, only allow the white list through.
def company_params
params.require(:company).permit(:name, :plan_id, users_attributes: [:id, :company_id, :email, :password, :password_confirmation, :first_name, :last_name, :role, :rate])
end
end
and
class UsersController < ApplicationController
# include UsersHelper
def index
#users = User.all
end
def new
#user = User.new
end
def create
#user = User.new(user_params)
#user.save
flash.notice = "User '#{#user.first_name} #{#user.last_name}' was successfully created."
redirect_to user_path(#user)
end
def show
#user = User.find(params[:id])
end
def edit
#user = User.find(params[:id])
end
def update
#user = User.find(params[:id])
#user.update(user_params)
flash.notice = "User '#{#user.first_name}' has been updated."
redirect_to user_path(#user)
end
def destroy
end
private
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:email, :password, :password_confirmation, :first_name, :last_name, :role, :rate)
end
end
and
class Company < ActiveRecord::Base
has_many :users
belongs_to :plan
accepts_nested_attributes_for :users, :allow_destroy => true
end
and
class User < ActiveRecord::Base
authenticates_with_sorcery!
validates_confirmation_of :password, message: "should match confirmation", if: :password
has_many :jobs
belongs_to :company
end
and
<%= form_for(#company) do |f| %>
<% if #company.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#company.errors.count, "error") %> prohibited this company from being saved:</h2>
<ul>
<% #company.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name, :id => "name" %>
</div>
<div class="field">
<%= collection_select( :company, :plan_id, #plans, :id, :name ) %>
</div>
<%= f.fields_for :user do |user| %>
<div class="field">
<%= user.label :email %><br>
<%= user.text_field :email %>
</div>
<div class="field">
<%= user.label :password %><br>
<%= user.password_field :password %>
</div>
<div class="field">
<%= user.label :password_confirmation %><br>
<%= user.password_field :password_confirmation %>
</div>
<div class="field">
<%= user.label :first_name %><br>
<%= user.text_field :first_name %>
</div>
<div class="field">
<%= user.label :last_name %><br>
<%= user.text_field :last_name %>
</div>
<div class="field">
<%= user.label :role %><br>
<%= user.text_field :role %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
and
ActiveRecord::Schema.define(version: 20140421235514) do
create_table "companies", force: true do |t|
t.string "name"
t.string "stripe_token"
t.integer "plan_id"
t.integer "user_id", limit: 255
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "companies", ["plan_id"], name: "index_companies_on_plan_id"
add_index "companies", ["user_id"], name: "index_companies_on_user_id"
create_table "plans", force: true do |t|
t.string "stripe_id"
t.string "name"
t.integer "amount"
t.string "interval"
t.string "currency"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", force: true do |t|
t.string "email", null: false
t.string "crypted_password", null: false
t.string "salt", null: false
t.datetime "created_at"
t.datetime "updated_at"
t.string "reset_password_token"
t.datetime "reset_password_token_expires_at"
t.datetime "reset_password_email_sent_at"
t.string "first_name"
t.string "last_name"
t.string "role"
t.integer "rate"
t.integer "company_id"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token"
end
Company and User are associated with 1-M Relationship , i.e., Company has_many :users
In that case, in your view for Company, the nested form should be
<%= f.fields_for :users do |user| %> ## Notice users in plural
and NOT
<%= f.fields_for :user do |user| %>
Refer to the Nested Attributes Examples for One to Many
Currently, fields_for is setup incorrectly with singular :user so in params hash you got the key as :user and again a warning Unpermitted parameters: user because of which the user attributes were not stored in database.
Now, as you have setup accepts_nested_attributes_for in Company model. Controller is expecting user attributes in key users_attributes within params hash.
Changing the fields_for with plural :users argument would result in creation of users_attributes key in params hash upon form submission.
UPDATE
Company has many users, its 1-M relationship
Only users table should have foreign key as company_id.
You need to remove user_id from companies table.
Also, update the CompaniesController#new action as below:
def new
#company = Company.new
#users = #company.users.build
#plans = Plan.all
end
Strong params permitting looks fine to me but i think the issue is in the nested form, you used wrong relation name user while its users which generates a params hash titled with user which is not permitted, instead you should do:
<%= f.fields_for :users do |user| %>
#rest of the form elements
<% end %>
I'm trying to add a user profile sub module to a user module but having some problems.
Routes:
resources :users do
resources :userprofiles
end
userprofiles_controller.rb:
class UserprofilesController < ApplicationController
def edit
#user = current_user
#user.UserProfile ||= UserProfile.new
#userprofile = #user.UserProfile
end
def update
#user = current_user
#user.UserProfile ||= UserProfile.new
#userprofile = #user.UserProfile
if #userprofile.update_attributes(:userprofile => params[:userprofile])
redirect_to #user
flash[:notice] = "Changes saved."
else
render 'edit'
flash[:notice] = "Error."
end
end
end
user_profile.rb:
class UserProfile < ActiveRecord::Base
attr_accessible :first_name, :last_name, :summary
belongs_to :user
end
Error:
Can't mass-assign protected attributes for UserProfile: userprofile
Line:
if #userprofile.update_attributes(:userprofile => params[:userprofile])
EDIT
Form:
<%= form_for([#user, #userprofile], url: user_userprofile_path(#user, #userprofile)) do |form| %>
<%= form.label :first_name %>
<%= form.text_field :first_name %>
<%= form.label :last_name %>
<%= form.text_field :last_name %>
<%= form.label :summary %>
<%= form.text_area :summary %>
<%= form.submit "Update", class: "btn btn-block btn-primary" %>
<% end %>
Table:
create_table "user_profiles", force: true do |t|
t.string "last_name"
t.string "first_name"
t.text "summary"
t.integer "user_id", null: false
t.datetime "created_at"
t.datetime "updated_at"
end
You just want
#userprofile.update_attributes(params[:userprofile])
That's a hash with keys :first_name, :last_name, and :summary, which are allowed attributes. When you try to update :userprofile => params[:userprofile], the model checks to see if the key :userprofile is allowed - and it isn't.
I also had this problem. The issue is that you still have attr_accessible in your model controller. Since you don't need them anymore with Rails 4 remove them, add your strong parameters to the controller, and you'll be able to mass-assign without issue.