我有一个projects/show.html.erb
页面。一个project has_many project_messages
,并从projects/show.html.erb
页中,用户可以成功创建新的project_message
,但是,当通过project_message
部分创建新的_form
时,页面刷新。
我想使用:remote => true将project_messages
添加到项目中,而不必刷新页面。
请参阅下面我使用的代码。这不起作用,并且页面仍刷新。我是Rails的新手,所以我们将不胜感激。
请在下面查看每个文件的代码
在projects/show.html.erb
中显示project_message并创建一个新的project_message,我有以下成功的代码:
<div class="au-chat au-chat--border">
<div class="au-message-list">
<% @project.project_messages.each do |project_message| %>
<%= render partial: 'project_messages/project_message', locals: { project_message: project_message } %>
<% end %><br>
</div>
<div class="au-chat-textfield">,
<%= render partial: 'project_messages/form', locals: { project_message: @project_message } %>
</div>
</div>
在project_messages_controller.rb
文件中,创建方法如下,我添加了format.js { }
def create
@project_message = ProjectMessage.new(project_message_params)
@project_message.user_id = current_user.id if current_user
@project_message.project_id = current_user.team.project_id if current_user
respond_to do |format|
if @project_message.save
format.html { redirect_to @project_message.project }
format.json { render :show, status: :created, location: @project_message }
format.js { }
else
format.html { render :new }
format.json { render json: @project_message.errors, status: :unprocessable_entity }
end
end
end
然后project_message
_form
部分包括:remote => true
<%= form_with(model: project_message, local: true, :remote => true) do |form| %>
<% if project_message.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(project_message.errors.count, "error") %> prohibited this project_message from being saved:</h2>
<ul>
<% project_message.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= form.text_field :pMessage, id: :project_message_pMessage, :class => 'au-input au-input--full au-input--h65', placeholder: 'Type a message' %>
<div class="actions" >
<%= form.submit "Send" %>
</div>
<% end %>
然后我在views / project_messages / create.js.erb中创建了一个新的create.js.erb
文件,并添加了以下代码:
# confirm file called
console.log('create.js.erb file');
# add new comment to end of comments section
$("#project_message").append("<%= j render(@project_message) %>");
使用上面的代码,页面仍然刷新。
当我从local: true
project_message
部分删除_form
时,它不会刷新并创建模型,但是projects/show.html.erb
视图未更新!
我使用了以下链接here以及关于stackoverflow的其他帖子
答案 0 :(得分:0)
响应做|格式|
format.js {渲染'project_messages / create.js'}
结束
答案 1 :(得分:0)
您似乎正在使用Rails 5
从您的代码中删除remote: true
和local: true
在here
中了解此内容并确保您使用id = {project_message
您的代码是$("#project_message").append("<%= j render(@project_message) %>");
所以检查您的HTML代码,是否有ID这样的元素
答案 2 :(得分:0)
您可以将传统的form_for用于http://guides.rubyonrails.org/working_with_javascript_in_rails.html#remote-elements
在您的视图中更新以下代码
line
,并确保您使用ID为decShow