【发布时间】:2014-06-29 17:55:10
【问题描述】:
用户流量:
- 用户 POSTS 表单表明他们拥有哪些项目
- 用户在您拥有 ItemName(刚刚提交的属性)和 Description(他们之前未要求的属性)的列中看到他们提交的项目列表
- 在此项目列表中,如果用户愿意,我现在想为用户提供修补说明的机会
额外的一点是视图中呈现的项目列表可以通过 Ransack gem 排序。所以问题是,在下面表单代码的 sn-p 中,如果@inventories 是 Ransack 使列表可在操作 'new '?
@inventories.each do |inventory|
form_for inventory do |f|
f.text_field ...
现在表单和所有内容都正确加载,但提交的描述没有在任何地方得到修补。
更多上下文和完整代码:
控制器代码:
def new
#initializes the parent object needed to create the initial inventory of items
@signup_parent = Signup.find_by_email(session[:signup_email])
#required by Ransack gem to display results
@q = @signup_parent.inventories.ransack(params[:q])
@inventories = @q.result.includes(:signup)
end
def create
@signup_parent = Signup.find_by_email(session[:signup_email])
items_to_be_saved = []
#at some point array is populated with list of items user selects in form
@signup_parent.inventories.create items_to_be_saved
end
def update
#since the form_fors are generated by an each do that simultaneously creates forms and generates list of existing items, I figured I'd need to follow the same convention as the 'new' action
@signup_parent = Signup.find_by_email(session[:signup_email])
@q = @signup_parent.inventories.ransack(params[:q])
@inventories = @q.result.includes(:signup)
redirect_to :action => 'new'
end
查看代码:
<% if @signup_parent.inventories.count > 0 %>
<div class="table-responsive">
<table class="table table-condensed table-hover">
<thead>
<tr>
<th><%= sort_link(@q, :item_name, "Item") %></th>
<th>Description</th>
<th colspan="5"></th>
</tr>
</thead>
<tbody>
<% @inventories.each do |inventory| %>
<tr>
<td><%= inventory.item_name %></td>
<td>
<% if inventory.description.blank? %>
<%= form_for inventory, url: {action: 'update'}, :html => {:class => "form-inline"} do |f| %>
<div class="form-group col-xs-9">
<%= f.text_field :description, class: "form-control", placeholder: "Add description" %>
</div>
<div class="form-group col-xs-3">
<%= f.submit "Update", class: "btn btn-default btn-large btn-block" %>
</div>
<% end %>
<% else %>
<%= inventory.description %>
<% end %>
</td>
<td>
<% if inventory.description.present? %>
<%= button_to %>
<!-- no clue, separate question (but feel free to solve!) need this button to, 1) ideal solution: "reactivate" form with the description so that users can edit what they've put in, 2) hacky solution: delete the description entirely so that users will have to re-enter it in the form that renders once description is blank again -->
<% end %>
<%= button_to 'Remove', inventory, method: :delete, class: "btn btn-default btn-large btn-block" %>
</td>
</tr>
<% end %>
</tbody>
</table>
</div>
<% else %>
<!-- if they don't have any items, they see the create form -->
<% end %>
路线
resources :inventories, only: [:new, :create, :destroy]
patch 'inventories', to: 'inventories#update'
【问题讨论】:
标签: ruby-on-rails forms ruby-on-rails-4 ransack