How to return the complete object from an associative table?

Asked

Viewed 94 times

0

The code below returns only the ID’s of their respective relationships, need that instead of returning user_id and role_id return the object user and role with the registration data. Take a look at my code:

class Dispute < ApplicationRecord
  ...
  has_many :users_with_roles, through: :roles, source: :users_roles
  ...
end

The current return is this:

=> #<ActiveRecord::Associations::CollectionProxy [#<UsersRole user_id: "6c566300-14b8-4099-949d-a06e058cc68f", role_id: "216fdc1d-d4d5-4f49-a80d-cb73f8648491">]>

The Model Relationship Code:

class UsersRole < ApplicationRecord
  belongs_to :user
  belongs_to :role
end

I appreciate any hint to resolve this issue. Thank you.

  • 1

    Have you tried using include? http://guides.rubyonrails.org/active_record_querying.html#Eager-loading-Multiple-Associations

  • 1

    Where will you use the object? It’s api or something like?

  • @Rmobdick is an alternative, thanks for the tip. @alex-Takitani managed to solve through the serializer by calling the element user and role directly. Now I don’t know if it’s the best alternative. It’s an api and I’m using serializer.

  • 1

    Serializer resolves, even to_json itself, see: https://www.tigraine.at/2011/11/17/rails-to_json-nested-includes-and-methods

1 answer

0


Can effect the result I want using Serializer. First set in serialize relationships:

class Dispute::UsersRolesSerializer < ActiveModel::Serializer
  belongs_to :user, serializer: Dispute::UserSerializer
  belongs_to :role, serializer: Dispute::RoleSerializer
end

And then I defined what data I want for presentation:

class Dispute::UserSerializer < ActiveModel::Serializer
  attributes :id, :name
end

class Dispute::RoleSerializer < ActiveModel::Serializer
  attributes :id, :name
end

This is the way I found it. There are probably other alternatives to this question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.