I'm doing a page in which users can request access to different areas of a company for that I use 2 Access models and another Request
The problem:
It is desired that users enter the access code (only codacc is not repeated) and this is validated to which access it belongs to and then save its access_id in the request table (the idea is that the users do not have the id of access)
The tables:
create_table "accesses", force: :cascade do |t|
t.string "area", limit: 255
t.string "codacc", limit: 255 => Unique
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "requests", force: :cascade do |t|
t.integer "access_id", limit: 4 =>reference a model access
t.integer "user_id", limit: 4 =>reference a model user
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
The models:
Access.rb:
class Access < ActiveRecord::Base
has_many :requests
end
Request.rb /// This is where the real problem is
class Request < ActiveRecord::Base
belongs_to :access
belongs_to :user
validate :access_id_exists
Protected
#///////////////// Aqui el problema
def access_id_exists
if Access.exists?(:codacc => self.access_id) then (compruebo que exista ese codigo que ingreso)
self.access_id = (aqui tengo que cambiar el código de acceso por el id del acceso)
else
errors.add(:access_id, 'A valid bar_id is valid. ')
end
end
end
The controller request:
def create
@request = Request.new(request_params)
@request.user_id = current_user.id //cambio el id user que pide el form por el usuario actual
respond_to do |format|
if @request.save
format.html { redirect_to @request, notice: 'Request was successfully created.' }
format.json { render @request, status: :created, location: @request}
else
format.html { render :new }
format.json { render json: @request.errors, status: :unprocessable_entity }
end
end
end