Home > Software engineering >  Ruby on Rails database foreign key relations
Ruby on Rails database foreign key relations

Time:10-02

I have these two tables users from devise and border_rot_imports. In the border_rot_imports table, I have:

Table "public.border_rot_imports"

issuing_officer_id  | integer
*****

Foreign-key constraints:
    "fk_rails_6d0f78c8a8" FOREIGN KEY (issuing_officer_id) REFERENCES users(id)

and under users table i got :

Referenced by:
Table "public.users"
*******
    TABLE "border_rot_imports" CONSTRAINT "fk_rails_6d0f78c8a8" FOREIGN KEY (issuing_officer_id) REFERENCES users(id)

MODELS

class BorderRotImport < ApplicationRecord
    belongs_to :users, foreign_key: :issuing_officer_id
end

class User < ApplicationRecord
     has_many :issuing_officer, class_name: 'BorderRotImport'
end

so now the question is, how do i gain access to all the fields under the user table from border_rot_imports.

so under my new.html.erb I have a form that stores data to the database. And my create function is as follows:

def create
    @border_rot_import = BorderRotImport.new(border_rot_import_params)
    @border_rot_import.time_in = Time.current
    @border_rot_import.date_in = Time.current
    @border_rot_import.issuing_officer_id = User.find(current_user).id

    #setting default values
    @border_rot_import.vin = 'N/A' unless @border_rot_import.vin? 
    @border_rot_import.license_plate_in = 'N/A' unless @border_rot_import.license_plate_in?

  #  respond_to do |format|
  #    if @border_rot_import.save
  #      format.html { redirect_to @border_rot_import, notice: "Border rot import was successfully created." }
  #      format.json { render :new, status: :created, location: @border_rot_import }
  #    else
  #      format.html { render :new, status: :unprocessable_entity }
  #      format.json { render json: @border_rot_import.errors, status: :unprocessable_entity }
  #    end
  #  end
  end

now the database has the id of the user, but now i need the username through @border_rot_import so that I can display it in a table in the index instead of the user id. If there is another approach please provide me with some links.

Thank you in advance.

CodePudding user response:

Did you try referencing the related object from your instance variable? Normally, you can use:

@instance.related_object.attribute_name

where @instance is @border_rot_import, related_object is the model that shares a relation with the BorderRotImport model (user in your case) and attribute_name is the attribute of User which you wish to display.

<%= @border_rot_import.user.name %>
  • Related