Results 1 to 4 of 4
Thread: Mongoid relationships
Nov 19, 2013, 04:56 #1
- Join Date
- Mar 2005
- 0 Post(s)
- 0 Thread(s)
Hello, I am new to Rails and I'm building an API.
I have 2 objects:
Team: name, leader (user object, person who manages the team), users (array of user objects for people in the team (not including the leader))
User: id, name, email, typical fields
Currently my front end sends back a team object as name, users (array of user ids), leader (user id).
My Create and Update look like this for team:
def update @team = Team.find(params[:id]) if @team.update_attributes!(accepted_params) render json: @team else render json: @team.errors, status: :unprocessable_entity end end
My Team model looks like this:
class Team include Mongoid::Document include Mongoid::Timestamps::Created include Mongoid::Timestamps::Updated # standard field :name # relationships has_one :leader, class_name: 'User' has_many :users, inverse_of: :team # define the users based on an array of people with the team id def users=(user_ids) self.users.clear user_ids.each do |id| User.find(id).update_attribute :team_id, self.id end self.users end end
My User model looks like this:
class User include Mongoid::Document include Mongoid::Timestamps::Created include Mongoid::Timestamps::Updated field :name ## Database authenticatable field :email, :type => String, :default => "" # users belong to a team belongs_to :team, inverse_of: :user end
I have a team serialiser like this:
class TeamSerializer < ActiveModel::Serializer attributes :_id, :name has_many :users has_one :leader end
The problem I have is that when I save the team (or create it), the leader object never gets saved, it seems to default leader to the first item in the users array.
Can anyone help me get the relationships right? Many thanks for any assistance.