ruby-on-railsrubyeruby

says my embedded ruby is nil or empty


edit page: the first line of embedded ruby is giving me the trouble

Edit Post

<%= form_for @post do |f|%> (this line is the problem)
  <p> 
    <%= f.label :title %>
    <%= f.text_field :title%>
  </p>
  <p>            
    <%= f.label :content %>
    <%= f.text_area :content%>
  </p>
  <p>
    <%= f.submit "Update post"%>
  </p>
<% end %>

Look at the edit post, is this the problem? it seems like i was doing everthimg right and i just can't figure it out.

Post Controller

class PostsController < ApplicationController
   def index
      @posts = Post.all 
   end 

   def show 
      @post = Post.find(params[:id])
   end

   def new
      @post = Post.new(params[:id])
   end

   def create  
      @post = Post.new(post_params)

      if @post.save
         redirect_to posts_path, :notice => "your post was saved"
      else
         render "new"
      end
   end 

private

   def post_params
      params.require(:post).permit(:title, :content)
   end

   def edit
      @post = Post.find(params[:id])
   end

Solution

  • The edit action is not visible as it is private and is not executed. Hence @post is nil. Move it above the private call

    def edit
      @post = Post.find(params[:id])
    end
    
    private
    
    def post_params
      params.require(:post).permit(:title, :content)
    end