Hey Matt, what’s the relationship or association between a ‘note’ and a ‘type’?
-Conrad
Hey Matt, what’s the relationship or association between a ‘note’ and a ‘type’?
-Conrad
What does the model files look like?
-Conrad
class Note < ActiveRecord::Base
has_many :type
end
class Type < ActiveRecord::Base
belongs_to :note
end
You're making it harder than it needs to be, and I don't think you're
understanding the relationships you are setting up.
Since a Note has many types, if you did this at the console:
note = Note.find :first
you would have a note. To list its types:
note.types
Since this is an array, you would have to find all the types this note
had if you wanted to, say, display them. Something like:
note.types.each do |type|
puts type.type_name
end
(in standard non-erb lingo)
If you were wanting to print all the types as you were trying to do in a view:
<% @notes.each do |note| %>
<% note.types.each do |type| %>
<%= h(type.type_name) %>
<% end %>
<% end %>
Or, more simply:
<% @notes.each do |note| %>
<%= h(note.types.join(", ") %>
<% end %>
I would consider getting rid of the name "type_name" and instead
calling it "name". Also, you might want "has_many :types" rather than
"has_many :type"
Thank you for your help with this. I knew I was looking into this and
making it harder than it needed to be. It ended up that when I started
second guessing myself I was troubleshooting the wrong issue.
I was getting nil values on some of my note types which was causing the
error and this was because I put the column in after I had initially set
up the database. Previous notes didn't have a type and thats where my
problem was. I was looking at it that I had my relationship set up
incorrectly and that I wasn't referencing it properly.