2014-06-10 4 views
1

하나의 열이있는 Word 모델 : word가 있습니다. 제출 될 때 @word 객체를 만드는 양식이 있습니다.for 루프를 사용하여 복수의 객체를 동시에 생성

단어/_form.html.erb

<%= form_for(@word, :remote => (params[:action] == 'new' ? true : false)) do |f| %> 
    <fieldset> 
    <div class="field"> 
     <%= f.text_field :word, :required => true %> 
    </div> 
    </fieldset> 

    <div class="actions"> 
    <%= f.submit :disable_with => 'Submitting...' %> 
    </div> 
<% end %> 

단어/create.js.erb

$('#words').prepend('<%= escape_javascript(render @word) %>'); 
$('#new-word-form-container').find('input:not(:submit),select,textarea').val(''); 

내가 simontaniously 하나 개의 양식 제출에 여러 단어의 생성을 나타내는 표현하고 싶습니다 (즉, 각 개별 단어를 만들기 위해 다시 제출하는 대신).

문자열을 단어 배열 (쉼표 또는 공백으로 구분)로 분할하는 내 Word 모델의 메서드가 있습니다.

class Word < ActiveRecord::Base 

attr_accessible :word 

    # Split Words method splits words seperated by a comma or space 
    def self.split_words(word) 
    # Determine if multiple words 
    if word.match(/[\s,]+/) 
     word = word.split(/[\s,]+/) # Split and return array of words 
    else 
     word = word.split    # String => array 
    end 
    end 

end 

나는 각 배열 요소를 단계별 및 요소에 대한 @word 객체를 생성하는 내 create 행동에서 루프를 사용하는 것을 시도하고있다.

class WordsController < ApplicationController 
respond_to :js, :json, :html 

def create 
    split = Word.split_words(params[:word]) 

    split.each do |w| 
    @word = Word.create(params[:w]) 
    respond_with(@word) 
    end 
end 

아래에 나열된 바와 같이 현재 HashWithIndifferentAccess 오류가 발생합니다.

Started POST "/words" for 127.0.0.1 at 2014-06-10 13:09:26 -0400 
    Processing by WordsController#create as JS 
     Parameters: {"utf8"=>"✓", "authenticity_token"=>"0hOmyrQfFWHRkBt8hYs7zKuHjCwYhYdv444Zl+GWzEA=", "word"=>{"word"=>"stack, overflow"}, "commit"=>"Create Word"} 
    Completed 500 Internal Server Error in 0ms 

    NoMethodError (undefined method `match' for {"word"=>"stack, overflow"}:ActiveSupport::HashWithIndifferentAccess): 
     app/models/word.rb:9:in `split_words' 
     app/controllers/words_controller.rb:36:in `create' 

모든 도움을 주시면 감사하겠습니다.

+0

당신은 당신의 양식을 게시 할 수 있습니다. – DickieBoy

+1

ActiveSupport :: HashWithIndifferentAccess 개체에 대해 일치 메서드를 사용할 수 없다고 생각하면 조건부 전에 표준 단어 루비 해시 개체로 단어 개체를 변환 할 수 있습니까? http://api.rubyonrails.org/classes/ActiveSupport/HashWithIndifferentAccess.html –

+0

그래, 콘솔에서 해본 적이 있는데, w = word.to_hash와 같은 것을 할 수 있습니다. w.match ... –

답변

2

단어 컨트롤러에서 create 동작에서 params의 단어를 가져 오면 parameter 개체가 다시 나타납니다. parameter 개체는 ActiveSupport::HashWithIndifferentAccess에서 상속받은 hash 개체와 같습니다. 그런 다음 parameter 개체에서 match 메서드를 호출하면 응답하는 방법을 알 수 없으므로 NoMethodError이 표시됩니다.

체크 아웃 http://api.rubyonrails.org/classes/ActionController/Parameters.html

당신이해야 할 첫 번째 일은, 이것은 당신에게 다시 string 객체를 제공한다 대신 params[:word]params[:word][:word]를 통과하고이 방법이 지금 작업을해야합니다.

each 루프의 다른 문제가 create에있는 것처럼 보일 수도 있습니다. params[:w]nil을 반환 할 수 있습니다. 대신 w을 전달해야합니다. 이는 각 단어가 array에 반복되어 반복되는 것이므로 각 단어에 대해 word 개체를 만들고 싶다고 착각하지 않는 경우입니다.

def create 
split = Word.split_words(params[:word][:word]) 

@words = split.map do |w| 
    Word.create(word: w) 
end 

respond_with(@words) 
end 
+0

"스택"쿼리를 사용할 때 NoMethodError가 발생합니다 (정의되지 않은 메서드 인 "stringify_keys"for "stack": String) : –

+0

Kyle.Belanger? params [word] [word]가 무엇을 반환하는지 말해 줄 수 있습니까?이'{ "word"=> "stack, overflow"}'나는 "stack, overflow"를 반환 할 것으로 예상했다. – mrageh

0
class WordsController < ApplicationController 

    respond_to :js, :json, :html 

    def create 
    @words = params[:word].split.map { |word| Word.create(word) } 
    respond_with(@words) 
    end 
end 
+2

이 답변은 삭제 표시되었지만 삭제하지는 않습니다. 그러나 솔루션 주변의 몇 마디로 답이 크게 향상되며 OP가 문제 해결 방법을 이해하는 데 도움이됩니다. –

+0

@RoboticCat에 동의합니다. 그러나이 여전히 관계없이 HashWithIndifferentAccess 오류를 반환합니다. –

관련 문제