【发布时间】:2018-09-14 01:49:26
【问题描述】:
我是 Rails 的新手,我正在尝试在数据库中保存新记录时使用 Action Cable 更新客户端。
为此,我有这个posts_controller.rb:
# POST /posts
# POST /posts.json
def create
@post = Post.new(post_params)
picture = params[:post][:picture]
respond_to do |format|
if @post.save
@post.picture.attach(picture) if picture.present?
PostsChannel.broadcast_to @post, html: render(partial: 'post', locals: { post: @post }) #<--- render
format.html { redirect_to posts_url, notice: 'Post was successfully created.' } #<--- redirect
format.json { render :show, status: :created, location: @post }
else
format.html { render :new }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
还有_post.html.erb:
<div class="cd-timeline__block js-cd-block">
<div class="cd-timeline__img cd-timeline__img--picture js-cd-img">
<p>????</p>
</div>
<div class="cd-timeline__content js-cd-content">
<%= image_tag post.picture.variant(resize: '400x400') %>
<p><%= post.text %></p>
<span class="cd-timeline__date"><%= post.created_at.strftime('%d/%m/%Y %T') %></span>
</div>
</div>
由于部分渲染和重定向,最终会出现错误 AbstractController::DoubleRenderError。问题是我不知道如何做到这一点。我不想在 JS 文件中生成 HTML,因为看到的是一些代码示例(我的帖子模板会有代码重复)。我一直在寻找其他示例,但没有任何帮助。
here 和 here 讨论了同样的问题,但我不知道如何使用 flash 来获得我想要的。
有什么建议吗?
【问题讨论】:
标签: ruby-on-rails ruby actioncable