Em Sta
Em Sta

Reputation: 1706

Rails undefined method `image' for error

I wanted to add to my rails app a new model:

rails g model Painting patient:references treatment:references image:string

I run migration, and then added some lines to the other controllers In the treatment model:

has_many :paintings

and in the patient controller

has_many :paintings, :through => :treatments

As well i updated the routes to:

resources :treatments do
 resources :paintings
end

So i hoped this is sufficent, to add an imageNAME to an treatment so that i configured the form for the treatment:

<%= form_for([@patient, @patient.treatments.build]) do |f| %>

 <div class="field" >
<%= f.label :content %>
<%= f.text_area :content %>
 </div>

 <div class="field" >
<%= f.label :day %>
<%= f.text_field :day, :value => Date.today %>
</div>

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

<div class="actions">
<%= f.submit nil, :class => 'btn btn-small btn-primary' %>
</div>

Now with the new :image form i get the error undefined method `image' for # So i hope somebody knows how to fix this problem! Thanks!

Upvotes: 0

Views: 1388

Answers (1)

th3sku11
th3sku11

Reputation: 76

I think that the problem is that the form helper is expecting 'image' to be a method of @patient, rather than 'treatment'. The fields_for helper might be what you need to access the attributes of a related model's fields. Something like this:

<% fields_for @patient.paintings do |paintings_fields| %>
  <div class="field" >
    <%= paintings_fields.label :image %>
    <%= paintings_fields.text_field :image %>
  </div>
<% end %>

See the docs for fields_for here: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for

Upvotes: 1

Related Questions