Undefined local variable in Rails Controller - ruby-on-rails

undefined local variable or method `dashboard_user' for #
Extracted source (around line #3):
class AdminController < ApplicationController
def user_creation
dashboard_user.create(:username => params[:username])
dashboard_user.create(:password => params[:password])
dashboard_user.create(:lastname => params[:lastname])
dashboard_user.create(:firstname => params[:firstname])
how do i fix this thanks i am new to ruby
After fixing this i am getting this
undefined method `attr_accessible' for
class DashboardUser < ActiveRecord::Base
self.table_name = "dashboard_user"
attr_accessible :username
attr_accessible :password
attr_accessible :lastname
attr_accessible :firstname
full controller
class AdminController < ApplicationController
def user_creation
DashboardUser.create(:username => params[:username])
DashboardUser.create(:password => params[:password])
DashboardUser.create(:lastname => params[:lastname])
DashboardUser.create(:firstname => params[:firstname])
DashboardUser.create(:middlename => params[:middlename])
DashboardUser.create(:phone => params[:phone])
redirect_to :action => 'user_creation'
end
private
def dashboard_params
params.require(:dashboard_user).permit(:id, :username, :password, :lastname, :firstname, :middlename , :phone)
end
end
create_table "dashboard_user", primary_key: "USER_ID", force: true do |t|
t.string "USER_NAME", limit: 50, null: false
t.string "NORMALIZED_USER_NAME", limit: 50
t.string "PASSWORD", limit: 50
t.string "LAST_NAME", limit: 50
t.string "FIRST_NAME", limit: 50
t.string "MIDDLE_NAME", limit: 50
t.string "PHONE", limit: 15
t.string "EMAIL_ID", limit: 100
t.integer "SEQ_QUES_ID"
t.string "SEQ_QUES_ANSWER", limit: 100
t.string "EXPIRE_PASSWORD_IND", limit: 1
t.date "EXPIRE_PASSWORD_DATE"
t.string "DEACTIVATED_IND", limit: 1
t.date "DEACTIVATED_DATE"
t.integer "ROLE_ID"
t.string "CREATED_BY", limit: 50
t.datetime "CREATED_DATE"
t.string "UPDATED_BY", limit: 50
t.datetime "UPDATED_DATE"
end
schema

On important rule in Rails is: Convention over Configuration
In convention your model file called dashboard_user but when you open that file, your model class name should be DashboardUser so following change to your code should solve the problem:
class AdminController < ApplicationController
def user_creation
DashboardUser.create(:username => params[:username])
DashboardUser.create(:password => params[:password])
DashboardUser.create(:lastname => params[:lastname])
DashboardUser.create(:firstname => params[:firstname])
end
end

In your controller you should be using the new permitted_params (As your using Rails 4)
It should look like this at the bottom of your controller
private
def dashboard_params
params.require(:dashboard_user).permit(:id, :user_name, :first_name, :last_name, :password)
end

Related

Encrypted Date of birth is not being saved in database of sinatra/ rails

Here is my code:
patient_profile.rb
class PatientProfile < ApplicationRecord
belongs_to :patient
............
attr_encrypted :dob, key: Base64.decode64(SECRET_KEY)
validates_presence_of :dob
end
db/migrate/20200618205840_patient_profiles.rb
class PatientProfiles < ActiveRecord::Migration[6.0]
def change
create_table :user_profiles do |t|
t.string :encrypted_gender
t.string :encrypted_gender_iv
t.string :encrypted_address
t.string :encrypted_address_iv
.....................
t.date :encrypted_dob
t.date :encrypted_dob_iv
t.integer :patient_id, index: true
t.timestamps
end
end
end
patients_controller.rb
class PatientsController < ApplicationController
# POST /api/v1/signup
post '/signup' do
patient = Patient.new(params[:patient])
patient.password = params[:patient][:password]
patient.unique_code = SecureRandom.hex(6)
patient.confirmation_token = (SecureRandom.random_number(9e4) + 1e4).to_i
patient.confirmation_sent_at = Time.now
if patient.save
token = JsonWebToken.encode(patient_id: patient.id)
send_email(patient,
"Account Verification",
"Your verification code is #{patient.confirmation_token}")
response = { patient: patient_response(patient), token: token }
[200, response.to_json]
else
halt 422, error_message(patient.errors.full_messages)
end
rescue ActiveRecord::RecordInvalid => error
halt 422, error_message(error.message)
end
In postman we can post date and it shows posted.
But in database dob field is null.
What's an issue with this?
Thanks in advance.
Here is log:
I changed:
t.date :encrypted_dob
t.date :encrypted_dob_iv
to
t.string :encrypted_dob
t.string :encrypted_dob_iv
and it works fine and saves encrypted dob in a database.

Why is my controller not saving my object in the database?

I am saving an entry object for CalendarEntry which is my model, but in the view when I click "Done" for some reason the object doesn't save.
In my point of view my controller is fine, but maybe the issue is there:
Controller
def create
#entry = CalendarEntry.new(entries_params)
binding.pry
if #entry.save
render 'admins/calendar_entries/index'
else
render 'admins/calendar_entries/new'
end
end
def entries_params
conversions
params.require(:calendar_entry).permit(:entry_type, :entry_level, :visible, :title, :publication_date, :expiration_date, :content, :phonenumber, :website, :state, :city, :address)
end
def conversions
params[:calendar_entry][:entry_type] = params[:calendar_entry][:entry_type].to_i
params[:calendar_entry][:entry_level] = params[:calendar_entry][:entry_level].to_i
end
Console
As you see in the console is asking me for two values "calendar_categories" and "calendar_entry_categories", but how it's supposed to ask it because my "CalendarEntry" only ask for the values in there,
P.D. The id, created_at and updated_at is generated automatically.
Update July/17 - 11:12pm
Schema defined here:
create_table "calendar_categories", force: :cascade do |t|
t.string "name"
t.string "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "calendar_entries", force: :cascade do |t|
t.integer "entry_type"
t.integer "entry_level"
t.boolean "visible"
t.string "title"
t.datetime "publication_date"
t.datetime "expiration_date"
t.text "content"
t.string "phonenumber"
t.string "website"
t.string "state"
t.string "city"
t.string "address"
t.string "profile_picture"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "calendar_entry_categories", force: :cascade do |t|
t.bigint "calendar_entry_id"
t.bigint "calendar_category_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["calendar_category_id"], name: "index_calendar_entry_categories_on_calendar_category_id"
t.index ["calendar_entry_id"], name: "index_calendar_entry_categories_on_calendar_entry_id"
end
Model defined here:
class CalendarEntry < ApplicationRecord
scope :visible, -> { where(visible: true) }
scope :invisible, -> { where(visible: false) }
scope :expired, -> { where('expiration_date < ?', Time.zone.now) }
scope :active, -> { where('expiration_date >= ?', Time.zone.now) }
has_many :calendar_entry_categories, dependent: :destroy
has_many :calendar_categories, through: :calendar_entry_categories
enum entry_type: %i[event program]
enum entry_level: %i[municipal statal federal injuve]
mount_uploader :profile_picture, CalendarEntryProfilePictureUploader
validates :entry_type, :entry_level, :visible, :title,
:expiration_date, :content, :phonenumber, :website, :state, :city,
:address, :calendar_categories,
:calendar_entry_categories, presence: true
validates :publication_date, presence: true, on: :update
validates :title, uniqueness: true
validates :phonenumber, numericality: { only_integer: true }
validates :phonenumber, length: { is: 10 }
validates_inclusion_of :entry_type, in: CalendarEntry.entry_types
validates_inclusion_of :entry_level, in: CalendarEntry.entry_levels
validate :expiration_date_range
before_validation :init, on: :create
private
def init
self.publication_date ||= Time.zone.now
end
def expiration_date_range
return if !expiration_date.nil? && expiration_date > publication_date
errors.add(:expiration_date, :past_expiration_date)
end
end
It looks like you're trying to validate the presence of calendar_categories and calendar_entry_categories in your model validations.
You won't be able to validate their presence, considering a CalendarEntryCategory cannot exist until a CalendarEntry exists, and a CalendarCategory might not always exist when a CalendarEntry is created.
Therefore, to get this to work, all you should have to do is remove
:calendar_categories, :calendar_entry_categories from the presence: true validations in your CalendarEntry model.

Ruby / Rails - Paperclip::Error in ModificationsController#create

Paperclip::Error in ModificationsController#create Modification model missing required attr_accessor for 'image_file_name'
Error:
Model: modification.rb
class Modification < ActiveRecord::Base
has_attached_file :image,
styles: { thumb: ["64x64#", :jpg],
original: ['500x500>', :jpg] },
convert_options: { thumb: "-quality 75 -strip",
original: "-quality 85 -strip" }
validates_attachment :image,
content_type: { content_type: ["image/jpeg", "image/gif", "image/png"] }
end
Controller: modifications_controller.rb
class ModificationsController < ApplicationController
def index
#modifications = Modification.order('created_at')
end
def new
#modifications = Modification.new
end
def create
#modifications = Modification.new(modification_params)
if #modifications.save
flash[:success] = "Modification contributed!"
redirect_to collection_path
else
render 'new'
end
end
private
def modification_params
params.require(:modification).permit(:image, :title)
end
end
Migration: _create_modifications.rb
class CreateModifications < ActiveRecord::Migration
def change
create_table :modifications do |t|
t.string :title
t.string :image_file_name
t.string :image_content_type
t.integer :image_file_size
t.timestamps null: false
end
end
end
Migration: _add_attachment_modification_to_profiles.rb
class AddAttachmentModificationToProfiles < ActiveRecord::Migration
def self.up
change_table :profiles do |t|
t.attachment :modification
end
end
def self.down
remove_attachment :profiles, :modification
end
end
Schema.rb
create_table "modifications", force: :cascade do |t|
t.string "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
...
create_table "profiles", force: :cascade do |t|
t.integer "user_id"
t.string "first_name"
t.string "last_name"
t.string "location"
t.string "modifications"
t.string "website"
t.text "bio"
t.datetime "created_at"
t.datetime "updated_at"
t.string "avatar_file_name"
t.string "avatar_content_type"
t.integer "avatar_file_size"
t.datetime "avatar_updated_at"
t.string "modification_file_name"
t.string "modification_content_type"
t.integer "modification_file_size"
t.datetime "modification_updated_at"
end
You declared twice has_attached_file :image method in your Model: modification.rb
Try to delete very first one has_attached_file :image and let me know if that works for you.

Rails: auto update reference table when update foreign_key

When i try to update foreign_key for table BusinessCard. It auto update the Company table without needed.
My Console Image
Can someone help me with this. Thanks
Edit---
My Controller
def update
#bc = BusinessCard.find_by(business_card_id: params[:id], deleted: false)
raise "名刺情報は存在しておりません。" unless #bc
raise "同じ名刺情報が存在しております。" if (#bc.name != params[:name] or #bc.email != params[:email] or #bc.company.name != params[:c_name]) and BusinessCard.joins(:company).where(name: params[:name], email: params[:email], deleted: 0, 'companies.name' => params[:c_name]).exists?
ActiveRecord::Base.transaction do
##bc.name = params[:name]
##bc.email = params[:email]
##bc.tel = params[:tel]
##bc.furigana = params[:furigana]
##bc.recieve_date = params[:recieve_date]
##bc.update_by = #current_user.user_id
#Company
#bc.company_id = bz_company if params[:c_name] and params[:c_post_code]
#department
##bc.department_id = bz_department if params[:d_name]
raise #bc.errors unless #bc.save
#images
#bz_omt if params[:i_omt]
#bz_ura if params[:i_ura]
end
render_json(#bc, :ok)
end
def bz_company
#company = Company.find_by(name: params[:c_name], post_code: params[:c_post_code])
#company = Company.new(name: params[:c_name], post_code: params[:c_post_code], create_by: #current_user.user_id) unless #company
#company.address = params[:c_address]
#company.email = params[:c_email]
#company.tel = params[:c_tel]
#company.fax = params[:c_fax]
#company.url = params[:c_url]
#company.deleted = 0
#company.update_by = #current_user.user_id
raise #company.errors unless #company.save
#company.company_id
end
BusinessCard Model
class BusinessCard < ApplicationRecord
#Association
#With Tag
has_many :map_tags, primary_key: 'business_card_id', foreign_key: 'business_card_id'
has_many :tags, :through => :map_tags
#with Comment
has_many :map_comments, primary_key: 'business_card_id', foreign_key: 'business_card_id'
has_many :comments, :through => :map_comments
#with Company
has_one :company, primary_key: 'company_id', foreign_key: 'company_id'
#with department
has_one :department, primary_key: 'department_id', foreign_key: 'department_id'
#with file_locations
has_many :file_locations, primary_key: 'business_card_id', foreign_key: 'business_card_id'
end
Company Model
class Company < ApplicationRecord
#Association
has_many :business_cards, primary_key: 'company_id', foreign_key: 'company_id'
end
Company Migration
class CreateCompanies < ActiveRecord::Migration[5.0]
def change
create_table :companies, id: false do |t|
t.column :company_id, 'INTEGER PRIMARY KEY AUTOINCREMENT'
t.string :name, limit: 150, null: false
t.text :address, limit: 1000, null: false
t.string :email, limit: 129
t.string :tel, limit: 20
t.string :fax, limit: 20
t.string :url, limit: 150
t.boolean :deleted, default: false
t.integer :create_by
t.integer :update_by
t.timestamps
end
end
end
BusinessCard Migration
class CreateBusinessCards < ActiveRecord::Migration[5.0]
def change
create_table :business_cards, id: false do |t|
t.column :business_card_id, 'INTEGER PRIMARY KEY AUTOINCREMENT'
t.string :name, limit: 50, null: false
t.string :furigana, limit: 50
t.string :email, limit: 129, null: false
t.string :tel, limit: 20, null: false
t.integer :owner_id
t.datetime :recieve_date
t.integer :company_id, null: false
t.integer :department_id, null: false
t.boolean :deleted, default: false
t.integer :create_by
t.integer :update_by
t.timestamps
end
add_index :business_cards, :business_card_id, :unique => true
end
end
Try this:
instead this in BusinnesCard Model
has_one :company, primary_key: 'company_id', foreign_key: 'company_id'
put this
belongs_to :company, primary_key: 'company_id', foreign_key: 'company_id'
PS Your code is little diry, i recommend you to replace primary_keys. For example, instead company_id, use id
You are using primary key column names that do not follow Rails' conventions. Therefore you have to tell Rails the names with primary_key= in your models:
# in app/models/company.rb
self.primary_key = 'company_id'
# in app/models/business_card.rb
self.primary_key = 'business_card_id'

Rails truncates hash on save:

I have a rails model with a hashed password field in it (surprise, surprise), which after some manipulation, is 40 characters long. I generate a user in script/console and it appears as follows:
#<User id: 1, firstname: "true", lastname: "false", username: "chaines51", hashed_password: "2Gr0GWvPunB3x5jomRTSTZJRIelC2RW103d7f3db">
I then run user_instance.save, which returns true, and the user then looks like this:
#<User id: 1, firstname: "true", lastname: "false", username: "chaines51", hashed_password: "103d7f3db">
Any idea what is happening to the other 30+ characters? I changed the field in the migration from string to text, but it still gets truncated
EDIT: The model code is:
require 'digest/sha1'
class User < ActiveRecord::Base
validates_presence_of :username, :password, :password_confirmation, :firstname, :lastname
validates_length_of :username, :within => 3..40
validates_length_of :password, :within => 5..40
validates_uniqueness_of :username
validates_confirmation_of :password
belongs_to :school
attr_protected :id, :salt
attr_accessor :password, :password_confirmation
def self.random_string(len)
#generate a random salt consisting of digits and letters.
chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
salt = ""
1.upto(len) { |i| salt << chars[rand(chars.size-1)] }
return salt
end
def password=(pass)
#password=pass
#salt = User.random_string(40-pass.length)
self.hashed_password = User.encrypt(#password, #salt)
end
def self.encrypt(pass, salt)
hash = Digest::SHA1.hexdigest(pass+salt)
hash.slice!(0..(40-pass.length-1))
hash = salt+hash;
end
def self.checkhash(pass, hash)
salt = hash.slice!(0..40-pass.length-1)
rehash = User.encrypt(pass, salt)
return rehash == (salt+hash)
end
def self.authenticate(login, pass)
u = User.find_by_username(login)
return nil if u.nil?
return u if User.checkhash(pass, u.hashed_password)
nil
end
end
and the db/schema.rb is:
ActiveRecord::Schema.define(:version => 20100127034504) do
create_table "categories", :force => true do |t|
t.string "title"
end
create_table "questions", :force => true do |t|
t.string "question"
t.string "a"
t.string "b"
t.string "c"
t.string "d"
t.string "e"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "questions_quizzes", :id => false, :force => true do |t|
t.integer "app_id"
t.integer "category_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "quizzes", :force => true do |t|
t.string "title"
t.integer "category_id"
end
create_table "schools", :force => true do |t|
t.string "name"
t.integer "coach_id"
end
create_table "users", :force => true do |t|
t.string "firstname", :null => false
t.string "lastname", :null => false
t.string "username", :null => false
t.boolean "needs_pass", :default => false
t.integer "school_id"
t.datetime "created_at"
t.datetime "updated_at"
t.boolean "confirmed", :default => false
t.text "hashed_password"
end
end
Showing the model code, and the table info form db/schema.rb, would be really helpful. Right off, I can tell you that a string column will hold up to 255 characters without a problem, so there might be something else at fault. If something is restricting, it will most likely show itself in one of the two places I named above.

Resources