gbarillot
gbarillot

Reputation: 329

Data manipulation inside a Phoenix model

(Coming from the Rails world, I'm now playing with Phoenix, trying to figure out how things work)

Starting from a scaffold, I have a User model containing "first_name" and "last_name" attributes, what I'd like to do now is concatenate them to a "full_name" attribute, in the model, and test it.

Ok, comparing Rails and Phoenix may not be the best thing to do, but let me show how I'd do it with Rails so my question could be perfectly understood:

# Model
class User < ActiveRecord::Base
  def full_name
    "#{first_name} #{last_name}"
  end
end

# Test
it "concatenates first_name and last_name" do
  user = users(:jhondoe)
  assert_equal "jhon doe", user.full_name
end

How can I achieve the same kind of thing using Phoenix, and is it even "the way to do it", since I cannot find anything related after hours of intensive googling?

Where and how do I deal with data manipulation using Phoenix?

Upvotes: 2

Views: 273

Answers (2)

NoDisplayName
NoDisplayName

Reputation: 15736

Concatenating first and last names must not be the responsibility of the model. You need to design your app and create special modules that would perform such things, some kind of decorators or whatever the right name for those in the functional programming.

But regarding the code, the Dogbert's answer is great.

Upvotes: 0

Dogbert
Dogbert

Reputation: 222158

As there are no methods in Elixir, the recommended way is to create a function in the User module for this, and explicitly invoke it whenever you want the full name of a User.

defmodule YourApp.User do
  ...

  def full_name(%YourApp.User{first_name: first_name, last_name: last_name}) do
    "#{first_name} #{last_name}"
  end
end

Then, in your tests, templates and/or views, invoke it like:

YourApp.User.full_name(user)

Sidenote: In Ecto 1.x, it was possible to create a virtual field and add after_load callbacks to set its value every time a model was loaded, but callbacks are being removed in Ecto 2.0 (which should be released soon) and so creating a function is the way to go.

Upvotes: 3

Related Questions