0

My setup:

class ServiceUser < ActiveRecord::Base
   belongs_to :user
   belongs_to :service

   enum status: [ :unavailable, :available ]
end

class Service < ActiveRecord::Base
  has_many :service_users
  has_many :users, :through => :service_users
end

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :service_users
  has_many :services, :through => :service_users
end

From the ServiceUser model i can call the status field, in my case available and unavailable. In my app i'm listing all the users for a specific service with:

@service.users

But now i want to show the status for each user from the ServiceUser model. What is the best way to do is?

Also i want to make a form for the ServiceUser model to make a new relation between the service and the current user:

ServiceUser.new(service_id: @service.id, user_id: current_user.id, status: 1)

What do i need to specify in the form for?

Matt Dice
  • 317
  • 2
  • 5
  • 14
  • Have a look at this answer -http://stackoverflow.com/questions/11180025/how-do-i-reference-and-change-an-extra-value-in-a-has-many-through-model – Edward Mar 05 '14 at 16:43

1 Answers1

0

Construct a hash with user_id as the key and value as the status

user_status = Hash[*@service.service_users.map{|su|[su.user_id, su.status] }.flatten]

Now you can get the status for each user by

@service.users.each do |user|
 p user_status[user.id]
end
usha
  • 28,973
  • 5
  • 72
  • 93
  • Thankyou that worked out! And now i want to create a form for the ServiceUser model, i added in the services_controller: @relation = ServiceUser.new And in the form form_for(@relation) do |f| But it's giving a routing error – Matt Dice Mar 08 '14 at 13:34