我正在遵循rails教程来学习它,我想学习涡轮增压.
这是我的index.html.erb视图:
<%= turbo_include_tags %>
<h1>Notes</h1>
<turbo-frame id="new_note">
<%= form_with(model: Note.new, url: notes_path) do |form| %>
<div>
<%= form.label :content %>
<%= form.text_area :content %>
</div>
<%= form.submit "Create Note" %>
<% end %>
</turbo-frame>
<turbo-frame id="notes">
<div>
<% @notes.each do |note| %>
<div>
<p><span><%= note.id %></span><%= note.content %></p>
<small> <%= note.created_at %> </small>
<%= link_to "Destroy", note_path(note), data: { turbo_method: :delete } %>
</div>
<% end %>
<%= link_to "New note", new_note_path %>
</div>
</turbo-frame>
My _list.html.erb模板:
<% notes.each do |note| %>
<div>
<p><span><%= note.id %></span><%= note.content %></p>
<small> <%= note.created_at %> </small>
<%= link_to "Destroy", note_path(note), data: { turbo_method: :delete } %>
</div>
<% end %>
这是我的控制器:
def index
@notes = Note.all.order(created_at: :desc)
end
...
def new
@note = Note.new
end
def create
@note = Note.new(note_params)
if @note.save
@notes = Note.all # Reload all notes or fetch them as needed
respond_to do |format|
format.turbo_stream do
render turbo_stream: turbo_stream.replace("notes", partial: "notes/list", locals: { notes: @notes })
end
format.html { redirect_to notes_url } # Fallback in case JavaScript is disabled
end
else
render :new
end
end
...
我想在单击提交按钮时创建新注释并更新列表. 我的代码中有两个问题. 第一个是验证后表格不干净.我不知道最好的方法.
第二个是刷新列表. 在我第一次点击提交按钮后,它只工作一次.如果不刷新页面,我无法创建第二个注释.另一个问题是新注释添加在列表的结尾而不是开头(因为我的列表是按照created_at值排序的).