ruby-on-railsmodelruby-on-rails-5attr-accessor

How do I populate an "attr_accessor" in my view?


I’m using Rails 5. I have this model with the following “attr_accessor” …

class Scenario < ApplicationRecord
  belongs_to :grading_rubric, optional: true
  has_many :confidential_memo
  has_many :scenario_roles, :dependent => :destroy
  has_many :roles, :through => :scenario_roles

  attr_accessor :roles_str

  validates_presence_of :title
  validates_presence_of :abstract

  def roles_str
    str = ""
    roles.each do |role|
      str = str.empty? ? "role.name\n" : "#{str}#{role.name}"
    end
    str
  end   
end

In my view, I would like to display the output of the above “roles_str” method in my “roles_str” text area. I have this set up

<%= form_for @scenario, :url => url_for(:controller => 'scenarios', :action => 'create') do |f| %>
…
    <%= f.text_area(:roles_str, cols: 40, rows: 20, :validate => true) %>

but when I edit my object, this field is not populated. How do I populate it with the specified output from the model’s “role_str” method?


Solution

  • The empty text area is likely because your roles_str is not an attribute in your database, but rather a simple accessor. To populate the text area, provide value manually, as suggested by @MarsAtomic in his now-deleted answer.

    <%= f.text_area(:roles_str, value: @scenario.roles_str, cols: 40, rows: 20, validate: true) %>
    

    The question is, what are you going to do when form is posted back? It won't be saved automatically (as there's no matching column in the table). But, I guess, it's out of scope of this question. :)