0

I created a small example in Ruby on Rails trying to understand how Turbo works in Ruby on Rails, this is what I did:

This is the index.html.erb, the idea here is to have a form with the list of posts created below

<p style="color: green"><%= notice %></p>

<h1>Posts</h1>

<%= turbo_frame_tag "post-feed" do %>
  <h2>Create a new post:</h2>
  <%= render "form" %>

  <h2>Post Feed:</h2>
  <%= render @posts %>
<% end %>

<%= link_to "New post", new_post_path %>

This is the file create.turbo_stream.erb

<%= turbo_stream.append "post-feed", partial: "posts/post", locals: { post: @post } %>

This is partial _form.html.erb, this form is embedded inside the index view:

<%= form_with(model: @post, data: { turbo_frame: "post-feed" }) do |form| %>
  <div>
    <%= form.label :title, style: "display: block" %>
    <%= form.text_field :title %>
  </div>

  <div>
    <%= form.label :body, style: "display: block" %>
    <%= form.text_area :body %>
  </div>

  <div>
    <%= form.submit %>
  </div>
<% end %>

This is posts_controller.rb

def create
    @post = Post.new(post_params)
    respond_to do |format|
      if @post.save
        format.html { redirect_to posts_path }
        format.turbo_stream
      else
        format.html { render :new }
        format.turbo_stream { render turbo_stream: turbo_stream.replace(@post, partial: 'posts/post', locals: { post: @post }) }
      end
    end
  end

# ...

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

But this is error when I hit the submit button: enter image description here

Any ideas on how to solve this or a brief example?

FerCib
  • 3
  • 1

1 Answers1

0

You say that you've embedded your form inside your index view, I'm guessing that your issue is that you forgot to set @post in your index method, so the form that's generated by form_with model: nil will not have the post wrapper around the attributes (ie. they'll be <input ... name="title"> instead of <input ... name="post[title]">) - so your params.require(:post) is failing.

Without seeing the rest of your code, it's hard to know for sure, but I think you can probably just set @post = Post.new in your index action.

smathy
  • 26,283
  • 5
  • 48
  • 68