我尝试做类似的事情,通过ajax为博客帖子添加评论,但我努力让它发挥作用。在我的项目中,用户可以有许多活动,每个活动可以有很多项目。
路由如下:
resources :users do
resources :activities do
resources :items
end
end
ActivitiesController.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
活动/ 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>
活动/ _item.html.erb
<tr>
<td><%= item.name %></td>
<td><%= item.cost %></td>
</tr>
项/ create.js.erb
#currently empty
答案 0 :(得分:0)
您的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>