2011-01-22 67 views
0

用户拥有多个网站,并且网站上有许多关键字。 (关键词是网站资源的嵌套资源)如何为文本区域中的每一行验证并创建新模型

现在,使用默认脚手架设置,一次添加多个关键字非常繁琐。我想要一个文本区域而不是文本区域,该区域允许用户输入多个关键字,每个关键字都是自己的,并一次提交。表单中唯一的输入是关键字的“文本”列。

我该怎么做?

我可以找出像params[:keyword][:text].split("\r\n").each do |text|这样的东西,但我不确定如何与Rails窗体进行交互。

<%= form_for [@website, @keyword] do |f| %> 
    <% if @keyword.errors.any? %> 
    <div id="error_explanation"> 
     <h2><%= pluralize(@keyword.errors.count, "error") %> prohibited this keyword from being saved:</h2> 

     <ul> 
     <% @keyword.errors.full_messages.each do |msg| %> 
     <li><%= msg %></li> 
     <% end %> 
     </ul> 
    </div> 
    <% end %> 

    <div class="field"> 
    <%= f.label :text %><br /> 
    <%= f.text_area :text %> 
    </div> 

    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 

回答

0

(注:我本来卡住这对原来的岗位作为编辑,所以我直接复制并粘贴它,所以它是最好的答案)

这里是我结束了在同时做。这是马虎(我是一个红宝石noob),但它保存有效的关键字,并呈现回失败的关键字列表“新”:

# keywords_controller 
def create 
    invalid_keywords = [] 
    valid_keywords = [] 
    params[:keyword][:text].split("\r\n").map(&:strip).delete_if {|text| text == ""}.each do |text| 
     keyword = @website.keywords.new(:text => text.downcase) 
     if keyword.save 
     valid_keywords << keyword 
     else 
     invalid_keywords << keyword 
     end 
    end 

    if invalid_keywords.empty? # All keywords saved 
     redirect_to @website, :notice => "Keyword(s) added" 
    else # These keywords didn't save 
     @keyword = @website.keywords.new(:text => invalid_keywords.map(&:text).join("\r\n")) 
     @errors = invalid_keywords.first.errors 
     flash[:success] = "#{valid_keywords.count} keywords were saved" 
     flash[:alert] = "#{invalid_keywords.count} keywords did not save (shown below)" 
     render :action => "new" 
    end 
end 
1

您是否考虑解析由逗号分隔的关键字(如果关键字是单个单词,甚至是spaces)?我认为这是更常见的...至少在我的经验。

对于逗号,它将如此简单:line.split(',')

而逗号后面&之前删除空格:line.split(/\s*,\s*/)line.split(',').map{|k| k.strip}