ruby-on-railspostgresqlreferenceruby-on-rails-5table-relationships

Rails 5 + postgresql table reference relation for multiple fields


I have posts and users tables and relation as below

  create_table "posts", force: :cascade do |t|
    t.string "title"
    t.integer "submitted_by_id"
    t.integer "user_id"
    t.index ["user_id"], name: "index_posts_on_user_id"
    ...

now I can get username for post as below

<% @posts.each do |post| %>
    <%= post.user.username %>
<% end %>

however in the posts table I also have submitted_by_id field which stores different user than the user_id

So how can I get the username of submitted_by_id? Do I need a separate relation for that?

Thank you!


Solution

  • You need to add relationship in the Post model like below

    belongs_to :submitted_by_user,
                class_name: 'User',
                primary_key: :id,
                foreign_key: 'submitted_by_id',
                optional: true    
    

    optional: true wont cause validation error for submitted_by_user presence

    So in UI you can access like

    <%= post.submitted_by_user.username %>
    

    https://apidock.com/rails/ActiveRecord/Associations/ClassMethods/belongs_to