我为用户、投资组合和照片提供了一个嵌套表单。基本上,用户可以通过上传另一种形式的照片来创建一个组合。但是,我想让他们有机会创建一个新的投资组合,从他们正在查看的当前投资组合中选择一些照片,并让resubmit in PortfolioController方法为他们创建一个新的组合。这些模型是:
class User < ActiveRecord::Base
has_many: portfolios
end
class Portfolio < ActiveRecord::Base
has_many: photos
belongs_to: user
end
class Photo < ActiveRecord::Base
belongs_to: portfolio
attr_accessor :move
end控制人是:
class PortfolioController < ApplicationController
//... some generic code
def resubmit
// This is where I need help
end
def display
@userPortfolio = Portfolio.where(:id => params[:uid]).first
end
end其观点是:
<%= simple_form_for @userPortfolio, :url => {:action => resubmit} do |f|%>
<%= f.label current_user.name %>
<% @images = @userPortfolio.photos %>
<% @images.each do |anImage| %>
<%= f.fields_for :anImage do |ff| %>
<%= ff.checkbox :move, :id => "move_#{anImage.id}" %><%=ff.label :move, "Move image #{anImage.name} to new portfolio?" %>
<% end %>
<% end %>
<%= f.submit "Create new portfolio" %>
<% end %>基本上,一旦用户点击提交,我希望resubmit方法创建一个新的组合,其中包含与所选照片相同的新照片集。也就是说,我希望根据用户选择的照片的属性创建portfolio的1条新记录和几条新记录photo (只要用户选择了多少),所以我需要访问表示所选照片的记录。如何访问用户选择的所有照片?我不能简单地在表单上创建一个有限的复选框控制器,因为显示的数量取决于当前组合中的照片数量。
发布于 2015-11-23 22:36:12
好吧,看来我想做的事情还是很简单的。不需要nested_form,simple_form做的也一样好。但我确信nested_form (如托利SK所建议的)也能做到这一点。重点是将attr_accessor:添加到代码中。
基本上,代码如下:
class User < ActiveRecord::Base
has_many: portfolios
end
class Portfolio < ActiveRecord::Base
has_many: photos
belongs_to: user
attr_accessor: photos_attributes // This is an important piece of code
end
class Photo < ActiveRecord::Base
belongs_to: portfolio
attr_accessor :move
end然后,我简单地修改了表单,如下所示(注意附加的:pid => params[:pid],这样我就可以在resubmit中找到我需要访问的投资组合,如果我需要访问它):
<%= simple_form_for @userPortfolio, :url => {:action => "resubmit", :pid => params[:pid]} do |f|%>
<%= f.label current_user.name %>
<% @images = @userPortfolio.photos
i = 0
%>
<%= f.fields_for :images do |ff| %>
<% anImage = @images[i] %>
<%= ff.checkbox :move, :id => "move_#{anImage.id}" %><%=ff.label :move, "Move image #{anImage.name} to new portfolio?" %>
<% i = i+1%>
<% end %>
<%= f.submit "Create new portfolio" %>
<% end %>当您点击submit并将表单发送到resubmit时,params字典包含以下内容:
{"utf8"=>"✓",
... more parameters
"portfolio"=>{"photos_attributes"=>{"0"=>{"move"=>"0",
"id"=>"1"},
"1"=>{"move"=>"0",
"id"=>"2"},
...
"4"=>{"move"=>"0",
"id"=>"5"}}},
"commit"=>"Submit Job",
"pid"=>"1"}现在,我可以迭代这些复选框,并将它们与resubmit中属于当前组合的所有照片进行比较。
def resubmit
@myImages = Portfolio.where(:id => params[:pid]).photos
// iterate through each image and use a counter to access
// the dictionary elements to see if they were checked
end发布于 2015-11-23 12:39:36
使用宝石nested_form或茧使元素动态。在后端,使用选定的项为新组合创建条目。
https://stackoverflow.com/questions/33868084
复制相似问题