2

Summary: I am pulling a list of user IDs from a members transaction table that is then used to generate a list of users from the database. This is then used to generate JSON sent to a page that lists users associated with an account.

Background: Scala code using Squeryl on Play! Framework

The Error: value id is not a member of Option[models.User] when mapping the users to the JSON generator

The Code: Here's code being used in succession to finally generate the JSON

def memberIds(accountId: Long) = { from(DB.members)(m =>
      where(m.accountId === accountId)
        select (m)).map(_.userId).toSet
  }

def membersToAccount(id: Long) = {
    memberIds(id).map( i => models.User.get(i))
  }

def listMembers(accountId: Long) = {
    Json(generate(Account.membersToAccount(accountId)
      .map(user => Map(
      "id" -> user.id,
      "name" -> user.name,
      "username" -> user.username
    ))))
  }

The Confusion: the User class contains an id val that looks like case class User( val id: Long, etc. I'm confused as to why it would create this error. Is it a problem with syntax or where I am mapping the users? Thanks!

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
crockpotveggies
  • 12,682
  • 12
  • 70
  • 140

2 Answers2

6

That's cause models.User is wrapped in Option container (actually, that is monad). It's like trying to call method of User directly on List of users, like: List(someUsers).id

Basically that means, that this value can be either Some (non null wrapper) or Nothing (just like null but better).

Moreover, it is better not to use get on Options, consider link above for details.

Community
  • 1
  • 1
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
  • LOL I posted my fix 9 seconds after your answer. However, I will accept yours because I appreciate the better technique and I'll fix the code after I read over Option a little more. Thanks! – crockpotveggies Feb 14 '12 at 07:56
2

Solved the issue. Each user object was wrapped in an option like Some(user). So to fix this, I had to use the .get method on each property.

def listMembers(accountId: Long) = {
    Json(generate(Account.membersToAccount(accountId)
      .map( user => Map(
      "id" -> user.get.id,
      "name" -> user.get.name,
      "username" -> user.get.emailAddress
    ))))
  }
crockpotveggies
  • 12,682
  • 12
  • 70
  • 140