While trying to implement a user show view with dynamic post creation, I encountered an issue when refreshing the page after successfully creating posts. The issue arises when the previously created posts are overwritten with null IDs. Additionally, I am unsure about the correct placement of the create.js.erb file - should it be in the views folder or the assets/javascripts folder?
Here is an overview of my setup:
UsersController
def show
@user = User.find(params[:id])
@posts = Post.all
@post = @user.posts.build
end
users/show.html.erb
<%= "user-id: #{@user.id}" %>
<ul id="posts">
<%= render :partial => @posts %>
</ul>
<%= form_for(@post, remote: true) do |f| %>
<%= f.hidden_field :user_id, :value => @user.id %>
<%= f.submit %>
<% end %>
PostsController
def create
puts params[:post][:user_id]
@user = User.find(params[:post][:user_id])
puts @user
@post = @user.posts.build()
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.js {}
format.json { render json: @post, status: :created, location: @post }
else
format.html { render action: "new" }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
Rails.logger.info(@post.errors.inspect)
end
end
def index
@posts = Post.all
@post = Post.new
end
posts/_post.html.erb
<li><%= @post.id %></li>
posts/create.js.erb
$("<%= escape_javascript(render @post) %>").appendTo("#posts");