View with data from different tables connected with foreign key
For my project, I try to understand how to let data view on a single view from different tables. I tried to implement the example of the Ruby on Rails Tutorial (http://ruby.railstutorial.org/chapters/user-microposts#sec:a_micropost_model). In this example I'm able to see the microposts of a user on the user's page. So what was I doing?
- I generated a table for user with
rails generate scaffold user name:string
+ rake db:migrate - I generated a table for microposts with
rails generate scaffold micropost content:string user_id:integer
- I added into db/migrate/..._create_microposts.rb
def self.up (...) add_index :microposts, :user_id add_index :microposts, :created_at end
- I added the foreign/primary-key- relations into microposts- model
belongs_to :user
& users- modelhas_many :microposts
- rake db:migrate
- I changed the users-Show-html-View: app/views/users/show.html.erb
<% unless @user.microposts.empty? %> <%= render @microposts %> < %end% >
- For the command "render", I paginated the micropostpage app/views/microposts/_micropost.html.erb with content
<% = micropost.content %> posted <% = time_ago_in_words(micropost.created_at)%> ago
I've already filled some content and rails console says that rails already knows the link between both tables. Anyways, if I open the show action, I get some error:
NoMethodError in Users#show
Showing c:/src/script/testtest2/app/views/users/show.html.erb where line #13 raised:
undefined method `model_name' for NilClass:Class
Extracted source (around line #13):
10: </p>
11:
12: <% unless @user.microposts.empty? %>
13: <%= render @microposts %>
14: <% end %>
15:
16: <%= link_to 'Edit', edit_user_path(@user) %> |
Rails.root: c:/src/script/testtest2
Application Trace | Framework Trace | Full Trace
app/views/users/show.html.erb:13:in `_app_views_us开发者_JAVA百科ers_show_html_erb___161211003_22878180__702430867'
app/controllers/users_controller.rb:18:in `show'
Request
Parameters:
{"id"=>"1"}
It seems like rails doesn't like "render", so what did I do wrong? Unluckily I skipped some chapters of the tutorial, because I just simply want to know how to list microposts on the User-show page. Do I need to define more? In the tutorial, there's much more code, but this code also contains lots of definition for the css-Stylesheet, so I'm confused which code is really necessary for simply solving my problem.
Replace <%= render @microposts %>
in show.html.erb with <%= render @user.microposts %>
精彩评论