【问题标题】:Rails: In-place editing is a thing but what about in-place creating?Rails:就地编辑是一回事,但就地创建呢?
【发布时间】:2016-01-20 04:26:16
【问题描述】:

我知道in-place editing 是一个东西。但是我该如何进行就地创作。

我将items 关联到一个类别。如果我希望页面显示类别 x 中的所有项目,并让用户能够从类别页面向类别添加新项目,并且类别中的项目列表会更新以显示添加的新项目全部没有页面正在完全刷新我该怎么做?

这种类型的东西有宝石吗?

【问题讨论】:

  • 我认为使用 ajax 添加数据就可以了。
  • 如果没有 gem 或其他已知方法,我会选择 ajax。
  • 解决方案是AJAX调用。你必须使用 javascript 来完成这项工作。

标签: ruby-on-rails ruby-on-rails-4 rubygems


【解决方案1】:

是的,宝石被称为Cocoon(如果你有nested fields)。

--

它会(手动)这样工作:

#config/routes.rb
resources :posts do
   resources :categories, only: [:new, :destroy] #-> url.com/posts/:post_id/categories
end

#app/controllers/posts_controller.rb
class PostsController < ApplicationController
   def show
      @post = Post.find params[:id]
   end
end

#app/controllers/categories_controller.rb
class CategoriesController < ApplicationController
   respond_to :js, :html, only: :new

   def new
      @post = Post.find params[:post_id]
      @post.categories.build
   end

   def destroy
      @post = Post.find params[:post_id]
      @category = Category.find params[:id]

      @post.categories.delete @category
   end
end

#app/views/categories/new.js.erb
$category = $("<%=j render "form", locals: { post: @post } %>");
$($category.html()).appendTo(".categories");

#app/views/categories/_form.html.erb
<%= form_for post do |f| %>
   <%= f.fields_for :categories, child_index: Time.now.to_i do |category| %>
      <%= category.text_field :x %>
   <% end %>
<% end %>

#app/views/categories/new.html.erb
<%= form_for @post, remote: true do |f| %>
   <div class="categories">
       <%= f.fields_for :categories do |category| %>
           <%= category.text_field :x %>
       <% end %>
   </div>
   <%= link_to post_new_categories_path(@post), remote: true %>
   <%= f.submit %>
<% end %>

这将通过 ajax 将新项目附加到您的 posts#show 视图中。它应该可以工作,尽管可能需要稍作调整。

【讨论】:

  • 看起来不错,我试一试,看看效果如何
  • 看起来行不通。我需要 2 个单独的表格。 1.用于保存类别和另一个以轻松添加新项目。这一切都在一个表单中提交
猜你喜欢
  • 2011-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多