Description: I am following the toy_app tutorial on: https://www.railstutorial.org/book/toy_app
I am having issues with an Exercise question under section 2.3.3
Question: Edit the user show page to display the content of the user’s first micropost. (Use your technical sophistication (Box 1.1) to guess the syntax based on the other content in the file.) Confirm by visiting /users/1 that it worked.
Within my app/views/users/show.html.erb file. I tried using my @micropost.content object to display any content associated with the user.
<p id="notice"><%= notice %></p> <p> <strong>Name:</strong> <%= @user.name %> </p> <p> <strong>Email:</strong> <%= @user.email %> </p> <p> <strong>Content:</strong> <%= (<%= @micropost.content %>) %> </p> <%= link_to 'Edit', edit_user_path(@user) %> | <%= link_to 'Back', users_path %>
NoMethodError in Users#show
undefined method 'content' for nil:NilClass
Do I need to generate a form_for for my posts for my app/view/user file? Or, because I'm setting my :content object within a private 'micropost_params' method in my microposts_controller.rb, that it will not allow object data transfer between controllers?
I tested within console the following lines of code to make sure association is working:
first_user = User.first first_user.microposts micropost = first_user.microposts.first micropost.user
I feel that I need to define a method within my User controller file that gives access to my :content object within my MicroPosts Class.
show action should look something like the following.
def show @user = User.find(params[:id]) @micropost = @user.microposts.first end
Now, in the view, you can access the micropost's content using
@micropost.content. What if the user has no microposts associated with him(hasn't written a micropost)? In that case,
@user.microposts.first will be
nil. If you're not sure what I mean, try playing with it in the rails console.
<% if @micropost %> <%= @micropost.content %> <% else %> <p> User has no microposts </p> <% end %>
Answer author Arun-kumar
Tickanswer.com is providing the only single recommended solution of the question How to use Ruby on Rails Associations? under the categories i.e ruby-on-rails , ruby , . Our team of experts filter the best solution for you.