0

I have an assignment with many assessments and am using fields_for to traverse the nested assessment information.

On the assessment I have an ID value that I want to translate to its name. I want to pass that ID to a helper and return back the string name but I can't seem to get to the ID value?

My code is

<%= form_for assignment do |f| %>
  <%= f.fields_for :assignmentassessments do |ff| %>
      <div class="row">
        <div class="col-4">
            <% strength_name(:strength_id) %>
        </div>

And the helper is

module AssignmentsHelper
  def strength_name(id)

    if id != nil
      @strength = Strength.find_by(id: id)
      @strength.name
    end
  end
end

I am getting undefined method name for nil:NilClass because when I pass :strength_id it is coming through as nil

user1107201
  • 63
  • 1
  • 7

1 Answers1

1

You pass symbol :strength_id as id this cause error:

def strength_name(id)
  # in this scope your argument id equal :strength_id
  # if :symbol return true
  # because in Ruby :symbol == true
  # but Strength.find_by(id: :symbol)
  # return nil 
  # @strenght equal nil
  # and raise undefined method name for nil:NilClass
  if id != nil
    @strength = Strength.find_by(id: id)
    @strength.name
  end
end

How you can solve this problem?

Just pass valid id to your helper.

Read Understanding Symbols In Ruby

Community
  • 1
  • 1
Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103
  • Thanks for the guidance. I'm still a bit confused about how to get the value. If I do `ff.text_field :strength_id` I get a text box with the right value in it – user1107201 Jan 17 '15 at 20:55
  • @user1107201 sorry but i can't understand what you mean, can you describe more info for me? what exactly you can't get? – Roman Kiselenko Jan 17 '15 at 20:57
  • I don't understand how I can pass `:strength_id` to my own helper and use the ID value to retrieve the matching name from the Strengths table the same way `ff.text_field` takes `:strength_id` and creates a text box and puts the actual id value into it – user1107201 Jan 17 '15 at 21:12
  • try `ff.object.strength_id` this should return same as `assignment.strength_id` – Roman Kiselenko Jan 17 '15 at 21:13