I know the issue here is that I am trying to save a nil value but I have been debugging for hours and I can't figure out what seems to be causing the value to be nil. This occurs when I hit post on the micropost button below the text field.
Microposts Controller
class MicropostsController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
def show
@user = User.find(params[:id])
@micropost = current_user.microposts.build
@microposts = @user.microposts.paginate(page: params[:page])
end
def create
if @micropost.save
flash[:success] = "Micropost created!"
redirect_to root_url
else
render 'show'
end
end
def destroy
end
private
def micropost_params
params.require(:micropost).permit(:content)
end
end
Micropost Model
class Micropost < ApplicationRecord
belongs_to :user
default_scope -> { order(created_at: :desc) }
validates :user_id, presence: true
validates :content, presence: true, length: { maximum: 140 }
end
View Show
<% provide(:title, @user.first_name) %>
<div class="row">
<aside class="col-md-4">
<section class="user_info">
<h1>
<%= gravatar_for @user %>
<%= @user.first_name %>
</h1>
</section>
</aside>
</div>
<div class="row">
<aside class="col-md-4">
<section class="user_info">
<%= render 'shared/user_info' %>
</section>
<section class="micropost_form">
<%= render 'shared/micropost_form' %>
</section>
</aside>
</div>
<div class="col-md-8">
<% if @user.microposts.any? %>
<h3>Microposts (<%= @user.microposts.count %>)</h3>
<ol class="microposts">
<%= render @microposts %>
</ol>
<%= will_paginate @microposts %>
<% end %>
</div>
Your create action should be
def create
@micropost = Micropost.new(micropost_params)
if @micropost.save
flash[:success] = "Micropost created!"
redirect_to root_url
else
render 'show'
end
end
By default instance variables are nil
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.