How to return the entire object from an associative table?

0

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

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

The current payback is this:

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

The relationship model code:

class UsersRole < ApplicationRecord
  belongs_to :user
  belongs_to :role
end

I appreciate any tips for resolving this issue. Thank you.

    
asked by anonymous 02.02.2017 / 13:54

1 answer

0

You can accomplish the result you want using Serializer. First I defined in the serializer the relationships:

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

And then I defined the data I want to submit:

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

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

That's the way I found it. There are probably other alternatives to this issue.

    
02.02.2017 / 17:01