Also you will make life much easier for yourself if you stick to the
rails
naming conventions, so the column names will be id, name, price,
country_id
and id, country_name.
Hi, I’m also new to rails and I’m trying the same thing. I’m extending
the Getting Started example to learn.
I’ve made an extra table called clients: (id | name) and I already
had the table posts: (id | title | content | created_at | updated_at
| client_id). The index view for posts loops through all the posts I
want to show the client name. I believe the way to do this is like
this:
<% @posts.each do |post| %>
<%=h post.client.name %>
<%=h post.title %>
[...]
I have set up all the assocations (posts belongs_to client, client
has_many posts) but it doesn’t work. I’m probably making a simple
mistake but hey, I’m new
This is pretty weird actually, in the show view the name is displayed
(nice!!!), but in the index view (the list of all the posts) it isn’t
working yet. The code for the index view (not working) is as I wrote
earlier:
<% @posts.each do |post| %>
<%=h post.client.name %>
<%=h post.title %>
[...]
The show view (which works) is like this:
Name:
<%=h @post.client.name %>
The error generated by the index view:
Showing app/views/posts/index.html.erb where line #12 raised:
You have a nil object when you didn’t expect it!
The error occurred while evaluating nil.name
Good job Mike that you got it working It’s pretty hard for me
starting with Rails, coming from a PHP/CodeIgniter background. The
convention over configuration is really great though! I also watched
some screencasts last night, very useful!
i hope you got it working by now…
anyway, I’ve got my problem solved like this.
i wrote
belongs_to :Country, :foreign_key => :Country_id
in products.rb … it means that the each products belongs to the
Country table
with the foreign_key of Country_id that matches with id field of the
Country table.
well, I got it mixed up with has_one and the belongs_to… ^^
anyway… then, in the view.html,erb file, i wrote
<%=h
product.Country.CountryName %>
inside the <[email protected] do… loop… %>
and i got it working.
I hope this makes sense to to you… I’m new too… so I’m not sure if
I’m on the right track
well I hope you get yours working with this, or with the better
solution
[…]
Showing app/views/posts/index.html.erb where line #12 raised:
You have a nil object when you didn’t expect it!
The error occurred while evaluating nil.name
This means that post.client is nil (hence error with post.client.name).
Are
you sure that all your posts have a client? You could use
<%= h post.client.name if post.client %>
which will at least let it show posts that have clients and show nothing
for
those that have not, while you work out why some (or all) not.
Colin
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.