【问题标题】:Update page with ajax on form submit - nested routes在表单提交上使用 ajax 更新页面 - 嵌套路由
【发布时间】:2015-01-01 03:46:06
【问题描述】:

我正在尝试做一些类似于通过 ajax 将 cmets 添加到博客文章中的事情,但我正在努力让它工作。在我的项目中,一个用户可以有很多活动,每个活动可以有很多项目。

路由如下:

resources :users do
  resources :activities do
    resources :items
  end  
end

ActivityController.rb

#rest of code

def show
  @activity = Activity.find(params[:id])
  @new_item = @activity.items.build
  @items = @activity.items.all.order('id DESC')
end

ItemsController.rb

#rest of code
def create

  @activity = Activity.find(params[:activity_id])

  @item = @activity.items.new(item_params)
  respond_to do |format|
    if @item.save
      format.html {redirect_to user_activity_path(@activity.user_id, @activity)}
      format.js
    else
      format.html {redirect_to :back}
    end
  end
end

activities/show.html.erb

<div class="row">

  <div class="large-6 large-offset-3 columns">

    <%= simple_form_for [@activity, @new_item], url: user_activity_items_path(@activity.user_id, @activity), remote: true do |f| %>

    <%= f.input :name, required: false, :wrapper_html => { class: 'large-8 columns name' } %>
    <%= f.input :cost, required: false, :wrapper_html => { class: 'large-4 columns cost' } %>

    <%= f.submit "Add Item", class: 'large-4 columns button' %>
   <% end %>

  </div>
</div>

<div class="row">

  <div class="large-6 large-offset-3 columns item-list">

    <table>
      <thead>
        <tr>
          <th>Name</th>
          <th>Cost</th>
        </tr>
      </thead>
      <tbody>
       <% @items.each do |item| %>
         <%= render 'item', item: item %>
       <% end %>
      </tbody>
    </table>

  </div>
</div>

activities/_item.html.erb

<tr>
  <td><%= item.name %></td>
  <td><%= item.cost %></td>
</tr>

items/create.js.erb

#currently empty

【问题讨论】:

  • 在没有 ajax 的情况下可以很好地存储所有数据?
  • 不确定您的意思?如果你问它是否在没有 ajax 的情况下工作,答案是肯定的
  • 你用过rails ujs吗?
  • 不是很多,不...
  • 好的,没问题。你能告诉我保存你的数据后意味着提交数据你想做什么吗?

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


【解决方案1】:

你的 create.js.erb 应该是这样的

$("#getItems").last('tr').after('<%= escape_javascript(render partial: "activities/item", :locals => { :item => @item })) %>');

并在显示页面上用我的替换它。

<div class="row">
  <div class="large-6 large-offset-3 columns item-list">
    <table>
      <thead>
        <tr>
          <th>Name</th>
          <th>Cost</th>
        </tr>
      </thead>
      <tbody id="getItems">
       <% @items.each do |item| %>
         <%= render 'item', item: item %>
       <% end %>
      </tbody>
    </table>
  </div>
</div>

【讨论】:

  • 感谢@SSR,我在item 上收到了来自_item.html.erb 部分的undefined local variable 错误
  • 请检查我在 create.js.erb 文件中的更新并将其替换为新的。
猜你喜欢
  • 1970-01-01
  • 2016-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-09
  • 2016-10-02
  • 2020-10-13
相关资源
最近更新 更多