Question

Here are the code snippets which are working for me

User Model

class User < ActiveRecord::Base

  def full_name
    [first_name,last_name].join(" ")
  end

  def full_name=(name)
    split = name.split(" ",2)
    self.first_name = split.first
    self.last_name = split.last
  end
end

Then here are the views files

Show File

<h1>
    <%= @user.full_name %>
</h1>

Edit File

<div class="field">
    <%= f.label :full_name %><br />
    <%= f.text_field :full_name %>
</div>

This works perfectly fine for me.

I have read attr_accessor works same as

  def full_name
    [first_name,last_name].join(" ")
  end

  def full_name=(name)
    split = name.split(" ",2)
    self.first_name = split.first
    self.last_name = split.last
  end

So I tried like

class User < ActiveRecord::Base
  attr_accessor :full_name
end

I am not able to figure out what else should be done.

Neither is shows complete name in show page nor update the same in the database when form gets submitted.

Was it helpful?

Solution

It is not correct. attr_accessor works like

def full_name
  @full_name
end

def full_name=(value)
  @full_name = value
end

It just creates primitive getter / setter for your instance variable. If you need any kind of advanced processing (split / join in your case), you need to define getter and setter method yourself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top