我有一个带有属性的用户模型(并非所有必需的)first_name,last_name,birthday,profession,pet_name。
用于注册,用户需要输入first_name和birthday。
我想以某种方式获取nil属性(在本例中为last_name和profession)并随机选择其中一个并制作一个表单,要求用户填写。
如果我@user.attributes.map{|k,v| v==nil ? k : nil}.compact
我可以获得nil属性。
如何使表单足够通用,以便可以在任何属性上使用此方法?
答案 0 :(得分:3)
您可以在控制器操作中填写@field以显示其他字段的表单,然后显示该字段的表单:
# controller action
def additional_form
@field = @user.attributes.select{|k,v| v.nil?}.keys.sample
if request.post?
@user.update_attributes(params[:user]) and redirect_to root_path
end
end
# view for this action (additional_form.html.erb)
<%= form_for @user do |f| %>
<%= f.text_field @field %>
<%= f.submit %>
<% end %>