ActiveRecord::RecordNotFound in WorkersController#create - ruby-on-rails

now i'm doing creating a worker with role. I have worker , role and worker_role. Now i have done the create worker form and have a selection to choose role. After done the form i need to role_id and worker_id store in worker_role table. I have try and it return me some error.
worker controller
def new
#worker = Worker.new
#worker.company_id = params[:company_id]
#role = Role.all
end
def create
#worker = Worker.new(worker_params)
#company_id = Company.find(params[:worker][:company_id])
#role_id = Role.all
if #worker.save
#worker_role = Role.find(params[:id]).worker_roles.create(worker: worker, returned: true)
#log_in #worker
flash[:success] = "Welcome to the Areca Supermarket System!"
redirect_to #worker
else
render 'new'
end
end
new.html.erb(the form)
<% provide(:title, "Register worker") %>
<h1>Create Worker</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_with(model: #worker, local: true) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
<%= f.label :email %>
<%= f.email_field :email, class: 'form-control' %>
<%= f.label :phone_number %>
<%= f.number_field :phone_number, class: 'form-control' %>
<%= f.label :address %>
<%= f.text_field :address, class: 'form-control' %>
<%= f.label :password %>
<%= f.password_field :password, class: 'form-control' %>
<%= f.label :role_id %>
<%= f.select(:role_id, Role.all.collect { |l| [ l.name, l.id] }, {class: "form-select"}) %>
<%= f.hidden_field :company_id , value: 2%>
<%= f.submit "Create worker", class: "btn btn-primary" %>
<% end %>
</div>
</div>
worker_role model
class WorkerRole < ApplicationRecord
belongs_to :worker
belongs_to :role
end
worker_role migration
create_table "worker_roles", force: :cascade do |t|
t.integer "worker_id"
t.integer "role_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
worker migration
create_table "workers", force: :cascade do |t|
t.string "name"
t.string "email"
t.integer "phone_number"
t.string "address"
t.integer "company_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
t.boolean "admin", default: false
end
Error show in website
parameter in website

Hi as mentioned in request params, I can see that role_id you are passing in params as
Parameters:
params = {"authenticity_token"=>"[FILTERED]",“worker"=>{"name"=>"Daniel", "“email"=:“daniel#example.com", “phone_number"=:"Q134657891",“address"=>"Alor Setar", “password"=>"[FILTERED]", “role id"=>"1", “company _id"=:"2",“commit"=>"Create worker"}
#you can access the role ID as below:
params[:worker][:role_id]
But you are using it in the controller as
#worker_role = Role.find(params[:id])
#this should be as below:
#worker_role = Role.find(params[:worker][:role_id]).worker_roles.create(worker: #worker)
# OR
#if you are permitting role id
#worker_role = Role.find(worker_params[:role_id]).worker_roles.create(worker: #worker)

Related

NoMethodError in SuppliersController#create undefined method `outlet_suppliers'

now I'm trying store data (supplier_id and outlet_id) to outlet_suppliers from create supplier form, but it shown some error which is undefined method `outlet_suppliers'. Below is my code:
suppliers controller
def new
#supplier = Supplier.new
#outlet = Outlet.all
#supplier.company_id = params[:company_id]
end
def create
#supplier = Supplier.new(supplier_params)
#company_id = Company.find(params[:supplier][:company_id])
#outlet_id = Outlet.all
if #supplier.save
#outlet_supplier = Outlet.find(params[:supplier][:outlet_id]).outlet_suppliers.create(supplier: #supplier)
redirect_to #supplier
else
render 'new'
end
end
new.html.erb
<% provide(:title, "Create Suppliers") %>
<h1>Create Supplier</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_with(model: #supplier, local: true) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
<%= f.label :address %>
<%= f.text_field :address, class: 'form-control' %>
<%= f.label :phone_number %>
<%= f.number_field :phone_number, class: 'form-control' %>
<%= f.label :outlet_id %>
<%= f.select(:outlet_id, Outlet.all.collect { |l| [ l.name, l.id] }, {class: "form-select"}) %>
<%= f.hidden_field :company_id , value: 2%>
<%= f.submit "Create Supplier", class: "btn btn-primary" %>
<% end %>
</div>
</div>
outlet_suppliers migration
create_table "outlet_suppliers", force: :cascade do |t|
t.integer "outlet_id"
t.integer "supplier_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
Error show in website
issue is with your model file as pointed out by #Sergio in a comment.
#app/models/outlet_supplier.rb
class OutletSupplier < ApplicationRecord
belongs_to :outlet
belongs_to :supplier
#...
end
#app/models/outlet.rb
class Outlet < ApplicationRecord
has_many :outlet_suppliers
#...
end
I hope this will help you.

Unpermitted parameters: :supplier, :outlet

now i'm doing a grocery website. I trying to build an order form that can choose select supplier and outlet,so admin can create order by choosing which supplier and outlet, but now it come out error say unpermitted parameters.
Orders Controller
class OrdersController < ApplicationController
def supplier
#supplier = Supplier.find(params[:id])
end
def outlet
#outlet = Outlet.find(params[:id])
end
def index
#orders = Order.all
end
def show
#order = Order.find(params[:id])
end
def new
#order = Order.new
#supplier = Supplier.all
#outlet = Outlet.all
end
def create
#order = Order.new(order_params)
#supplier_id = Supplier.all
#outlet_id = Outlet.all
if #order.save
flash[:success] = "Succesful create!"
redirect_to #order
else
render 'new'
end
end
private
def order_params
params.require(:order).permit(:supplier_id,:grand_total, :order_date,
:delivery_date, :delivery_address, :outlet_id)
end
end
new.html.erb
<% provide(:title, "Create Orders") %>
<h1>Create Order</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_with(model: #order, local: true) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.label :supplier %>
<%= f.select(:supplier, Supplier.all.collect { |l| [ l.name, l.id] }, {class: "form-select"}) %>
<%= f.label :grand_total %>
<%= f.number_field :grand_total, class: 'form-control' %>
<%= f.label :order_date %>
<%= f.date_field :order_date, class: 'form-control' %>
<%= f.label :delivery_date %>
<%= f.date_field :delivery_date, class: 'form-control' %>
<%= f.label :delivery_address %>
<%= f.text_field :delivery_address, class: 'form-control' %>
<%= f.label :outlet %>
<%= f.select(:outlet, Outlet.all.collect { |l| [ l.name, l.id] }, {class: "form-select"}) %>
<%= f.submit "Create order", class: "btn btn-primary" %>
<% end %>
</div>
</div>
Order migration table in schema
create_table "orders", force: :cascade do |t|
t.integer "supplier_id"
t.integer "grand_total"
t.date "order_date"
t.date "delivery_date"
t.string "delivery_address"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "outlet_id"
end
parameter in console
error in website
The reason you're getting
Unpermitted parameters: :supplier, :outlet
is because you're not allowing :supplier and :outlet params but :supplier_id and :outlet_id in order_params
The Fix
Change this in your view new.html.erb
<%= f.label :supplier_id %>
<%= f.select(:supplier_id, Supplier.all.collect { |l| [ l.name, l.id] }, {class: "form-select"}) %>
<%= f.label :outlet_id %>
<%= f.select(:outlet_id, Outlet.all.collect { |l| [ l.name, l.id] }, {class: "form-select"}) %>
This should fix the issue by allowing the :supplier_id and :outlet_id params and assigning the object with proper values

UsersController Method Error 'title'. No Title in view?

Reposting due to formatting errors in previous post.
I am getting the below error, I've added code below for the whole MVC. The strange thing here is the controller wants a 'title' method to be included but I don't have a title requirement anywhere else, could this be referring to something else. While this isn't working the def update method won't patch so I can't save any user updates or new data to the system (it's a HRIS system btw).
So the error is;
NoMethodError in UsersController#update
undefined method `title' for #<User:0x007ff3dd9f8a70>
Extracted source (around line #56):
54
55
56
57
58
59
def update
#user = User.find(params[:id])
if #user.update_attributes(user_params)
flash[:success] = "Information Updated"
redirect_to #user
#handle successful update
Here is my Schema;
create_table "users", force: :cascade do |t|
t.string "name"
t.string "employee"
t.string "email"
t.string "password"
t.date "startdate"
t.date "probationcomp"
t.date "annualreview"
t.text "address"
t.string "phonenumber"
t.string "nextofkin"
t.string "kinnumber"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
t.boolean "admin", default: false
t.string "leavenum"
t.string "avatar_file_name"
t.string "avatar_content_type"
t.integer "avatar_file_size"
t.datetime "avatar_updated_at"
t.boolean "hstrain"
t.boolean "induction"
t.boolean "lhtrain"
t.boolean "vodatotal"
t.boolean "commtrainops"
t.boolean "commtrainsell"
t.boolean "hosttrainops"
t.boolean "hosttrainsell"
t.boolean "cpstrainops"
t.boolean "cpstops"
t.boolean "cpstsell"
t.string "leaverem"
t.text "specialism"
t.string "shelf"
t.string "doc_file_name"
t.string "doc_content_type"
t.integer "doc_file_size"
t.datetime "doc_updated_at"
end
The view;
<h1>Change your profile settings</h1>
<div class="row">
<%= form_for #user do |f| %>
<%= render 'shared/error_messages' %>
<!-- left side -->
<div class="col-md-6">
<%= f.label :password %>
<%= f.password_field :password, class: 'form-control' %>
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation, class: 'form-control' %>
<%= f.label :address, "Home Address" %>
<%= f.text_area :address, :cols => "1", :rows => "5", class: "form-control" %>
</div>
<!-- right side -->
<div class="col-md-6">
<%= f.label :phonenumber, "Contact Number" %>
<%= f.text_field :phonenumber, class: "form-control" %>
<%= f.label :nextofkin, "Emergency Contact Person" %>
<%= f.text_field :nextofkin, class: "form-control" %>
<%= f.label :kinnumber, "Emergency Contact Phone Number" %>
<%= f.text_field :kinnumber, class: "form-control" %>
<div class="gravatar_edit">
<%= gravatar_for #user %>
<a href="https://gravatar.com/emails" target=_blank>Change Profile Pic</a>
</div><br><p><br>
<%= f.submit "Save Changes", class: 'btn btn-warning' %>
<% end %>
</div>
</div>
The controller (this is where I think the error is, though update function looks fine, I haven't posted the whole controller, but can do if it helps)
def edit
#user = User.find(params[:id])
end
def update
#user = User.find(params[:id])
if #user.update_attributes(user_params)
flash[:success] = "Information Updated"
redirect_to #user
#handle successful update
else
render 'edit'
end
end
private
def user_params
params.require(:user).permit(:name, :employee, :email, :password, :startdate, :probationcomp,
:password_confirmation, :annualreview, :address, :phonenumber, :nextofkin, :kinnumber,
:created_at, :updated_at, :password_digest, :admin, :leavenum, :avatar_file_name, :avatar_content_type, :avatar_file_size,
:avatar_updated_at, :hstrain, :induction, :lhtrain, :vodatotal, :commtrainops, :commtrainsell, :hosttrainops,
:hosttrainsell, :cpstrainops, :cpstops, :cpstsell, :leaverem, :specialism, :shelf, :doc_file_name, :doc_content_type,
:doc_file_size, :doc_updated_at)
end
Finally the model;
class User < ApplicationRecord
attr_accessor :remember_token
before_save { email.downcase! }
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true,
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
validates :password, presence: true, length: { minimum: 7 }, allow_nil: true
#set up "uploaded_file" field as attached_file (using Paperclip)
searchable do
text :name, :id, :phonenumber
end
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::password.create(string, cost: cost)
end
def User.new_token
SecureRandom.urlsafe_base64
end
def remember
self.remember_token = User.new_token
update_attribute(:remember_digest, User.digest(remember_token))
end
def authenticated?
return false if remember_digest.nil?
BCrypt::Password.new(remember_digest).is_password?(remember_token)
end
def forget
update_attribute(:remember_token, nil)
end
end
I'm sure someone has had this issue before, just can't see the wood for the trees. test script comes back with same error.

has_many build AssociationTypeMismatch Error

Another newb question. A Band has_many Albums. I'm getting the error:
ActiveRecord::AssociationTypeMismatch (Band(#70076964285020) expected,
got "1" which is an instance of String(#12787800)):
app/controllers/albums_controller.rb:20:in `create'
... which is the build line in #create
albums controller
def new
binding.pry
#band = Band.find(params[:band])
authorize #band, :admin?
#album = Album.new
respond_to do |format|
format.js
end
end
def create
binding.pry
#band = Band.find(params[:album][:band].to_i)
authorize #band, :admin?
#album = #band.albums.build(album_params)
if #album.save
#albums = #band.albums
##eps = #band.eps
#songs = #band.songs
respond_to do |format|
format.js
end
else
#fail = "fail"
respond_to do |format|
format.js
end
end
end
def album_params
params.require(:album).permit(:band, :album_name, :album_release_date, :etc)
end
the form:
<%=simple_form_for(#album, remote: true, :authenticity_token => true, format: :js) do |f| %>
<%= f.hidden_field :band, :value => #band.id %>
<%= f.input :album_name %>
<%= f.input :album_release_date %>
<%= f.input :etc %>
<div id="albumsubmit">
<div class="form-actions">
<%= f.button :submit, "Create Album", class: "btn btn-primary" %>
</div>
</div>
schema
create_table "albums", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.bigint "band_id"
t.string "album_name"
t.string "album_release_date"
t.index ["band_id"], name: "index_albums_on_band_id"
end
when you passing to save method param with that have has_many Association he expect the instance of "band", just set the param name to band_id
here:
<%= f.hidden_field :band, :value => #band.id %>
to:
<%= f.hidden_field :band_id, :value => #band.id %>
and here:
params.require(:album).permit(:band, :album_name, :album_release_date, :etc)
to:
params.require(:album).permit(:band_id, :album_name, :album_release_date, :etc)

unknown attribute 'category_id' for Post

I am trying to create categories for my posts. To do so, I generated a new category model. Although I have associated the two models, I am still receiving this error:
ActiveRecord::UnknownAttributeError: unknown attribute 'category_id' for Post.
I have doublechecked the schema which does include category_id for the post table:
add_index "comments", ["post_id"], name: "index_comments_on_post_id"
create_table "posts", force: :cascade do |t|
t.string "title"
t.text "description"
t.string "cost"
t.integer "openspots"
t.boolean "approval"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.integer "category_id"
end
add_index "posts", ["user_id"], name: "index_posts_on_user_id"
Here are my associations as well:
class Category < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :user
belongs_to :category
has_many :comments
default_scope { order('created_at DESC') }
end
Finally I wanted to include my posts controller:
class PostsController < ApplicationController
def new
# #post = Post.new
#post = Post.new
#categories = Category.all.map{|c| [ c.name, c.id ] }
end
def create
#post = Post.new(params.require(:post).permit(:title, :description, :cost, :openspots, :approval, :category_id))
#post.category_id = params[:category_id]
#post.user = current_user
if #post.save
flash[:notice] = "Post was saved."
redirect_to #post
else
flash[:error] = "There was an error saving the post. Please try again."
render :new
end
end
def update
#post = Post.find(params[:id])
#post.category_id = params[:category_id]
if #post.update_attributes(params.require(:post).permit(:title, :description))
flash[:notice] = "Post was updated."
redirect_to #post
else
flash[:error] = "There was an error saving the post. Please try again."
render :edit
end
end
def edit
#post = Post.find(params[:id])
#post.category_id = params[:category_id]
end
def destroy
end
def index
#posts = Post.all
end
def show
#post = Post.find(params[:id])
end
end
Whenever I create a new post, the post is created successfully;however, the category id is never saved.
Here is my view as well:
<h1>New Post</h1>
<div class="row">
<div class="col-md-4">
<p>Guidelines for posts</p>
<ul>
<li>Make sure it rhymes.</li>
<li>Don't use the letter "A".</li>
<li>The incessant use of hashtags will get you banned.</li>
</ul>
</div>
<div class="col-md-8">
<%= form_for #post do |f| %>
<div class="form-group">
<%= f.label :title %>
<%= f.text_field :title, class: 'form-control', placeholder: "Enter post title" %>
</div>
<div class="form-group">
<%= f.label :description %>
<%= f.text_area :description, rows: 8, class: 'form-control', placeholder: "Enter post description" %>
</div>
<div class="form-group">
<%= f.label :cost %>
<%= f.number_field :cost, rows: 8, class: 'form-control', placeholder: "Enter cost" %>
</div>
<div class="form-group">
<%= f.label :openspots %>
<%= f.number_field :openspots, rows: 8, class: 'form-control', placeholder: "Enter Number of Open Spots" %>
</div>
<div class="form-group">
<%= f.label :approval %>
<%= f.check_box :approval, rows: 8, class: 'form-control', placeholder: "Check if Approval Necessary" %>
</div>
<div class="form-group">
<%= f.label :category %>
<%= f.collection_select :category_id, Category.order(:name),:id,:name, include_blank: true %>
</div>
<div class="form-group">
<%= f.submit "Save", class: 'btn btn-success' %>
</div>
<% end %>
</div>
</div>

Resources