2016-07-20 4 views
1

私は、次のモデルがあります:has_manyのは、フォーム内のテーブルの属性に参加

class RandomExam < ActiveRecord::Base 
    has_many :random_exam_sections 
    has_many :sections, :through => :random_exam_sections 
end 

class Section < ActiveRecord::Base 
    has_many :random_exam_sections 
    has_many :random_exams, :through => :random_exam_sections 

class RandomExamSection < ActiveRecord::Base 
    belongs_to :random_exam 
    belongs_to :section 
end 

アイデアがランダム試験を作成するための特定の構成を持つことがあるので、この表はまた、あなたが必要なのですかどのセクションを選択するのに役立つとここでは、セクションごとの質問の数を選択し、各テーブルの属性は次のとおりです。

RandomExam:名前(文字列)、のcreated_at(日時)、updated_atの(日時)

セクション:名前(文字列)、のcreated_at(日時)、updated_atの(日時)

RandomExamSection:random_exam_id(整数)、SECTION_ID(整数)、questions_number(整数)

あなたが見ることができるようにセクション属性ごとの質問の数はRandomExamSectionsテーブル内にあると私はという形でそれをアクセスしたいです

<%= form_for (@random_exam) do |f| %> 
    <div class="row"> 

     <div class="input-field col s12"> 
      <%= f.label :name, 'Name' %> 
      <%= f.text_field :name, placeholder: 'Enter the name of the  configuration' %> 
     </div> 

    </div> 

    <% @sections.each do |section| %> 

     <div class="row <%= dom_id(section) %>"> 
      <div class="col s4"> 
       <%= check_box_tag 'random_exam[section_ids][]', section.id, 
       @random_exam.section_ids.include?(section.id), id:  dom_id(section), class: "section-checkbox #{dom_id(section)}" %> 
       <%= label_tag dom_id(section), (raw sanitize  section.name, tags: %w(h2 p strong em a br b i small u ul ol li  blockquote), attributes: %w(id class href)), 
       class: "name #{dom_id(section)}" %> 
      </div class="col s4"> 
      <div> 
       <%= text_field_tag "random_exam[random_questions_numbers][#{section.id}][]", nil, 
            :placeholder => 'Enter the number of questions' %> 
      </div> 

     </div> 
    <% end %> 

    <div class="form-group"> 
     <%= f.submit class: "btn waves-effect waves-light green" %> 
    </div> 

<% end %> 

マイコントローラ:

def create 
    @random_exam = RandomExam.new(random_exam_params) 
    if @random_exam.save 
    assign_random_questions_number 
    flash[:success] = 'Random configuration created successfully' 
    redirect_to @random_exam 
else 
    flash.now[:danger] = @random_exam.errors.full_messages.to_sentence 
    render 'new' 
end 

def assign_random_questions_number 
    if params[:random_exam][:'random_questions_numbers'] == nil 
    return 
    end 


params[:random_exam][:'section_ids'].each do |key, value| 
    record = RandomExamSection.search_ids(@random_exam.id, key) 

    record.each do |random_exam_section_record| 
    number_of_questions = params[:random_exam][:'random_questions_numbers'][key].first.to_i 
    random_exam_section_record.update(questions_number: number_of_questions) 
    end 
end 

エンド

01 RandomExamコントローラから表示され、ここで私のフォームです

私はTypeError例外を取得しています:TypeError: nil is not a symbol nor a string私はこの方法でassign_random_questions_number

をレコードを更新するとき、私は、コンソール

random = RandomExamSection.first 
random.update(questions_number: 10) 

または私は実行でこれを実行すると、このエラーも表示されます。

random = RandomExamSection.first 
random.questions_number = 10 
random.save 

EDIT

私は関連付けiを削除しましたN RandomExamSectionとquestions_number

おかげでそれ内部の 'assign_random_questions_number' を再作成。

+0

ハイテクを支援し、スタックオーバーフローを歓迎することができます。だから - 私はすべてのセクションの数の任意のフォームフィールドが存在しないことに注意してください。あなたがもしあれば、あなたがそれをしようとしたとき、エラーがあなたが見た、何をしている作品を作るためにあなたの形で入れてみましたし、何がありますか? –

+0

@TarynEastよく、いくつかのスタックオーバーフローの答えを試しましたが、問題はネストされたフィールドを使用していることです。実装では使用していません。実際には、我々はそれを保存するとき、それは表示されませんので、フィールドが命名すべきか見当がつかない。 – Dazt

+0

...あなたの試したことを見せて(あなたの質問を編集してそこに置く)、それが現れるように修正するのを手助けすることができます:) AFAICTは別のフィールドです...あなたが望む名前の別のフィールドを追加してください。 –

答えて

1

あなたがnested_attributesを使用している場合は、このような何かを行うことができます。

#form 
<h4>Selected exams</h4> 
<%= f.fields_for :random_exam_sections do |b| %> 
    <%= b.hidden_field :section_id %> 
    <%= b.label :selected, b.object.section.name %> 
    <%= b.check_box :selected, { checked: !b.object.id.blank? } %> 
    <br> 
    <%= b.label :question_numbers %> 
    <%= b.text_field :questions_number %> 
<% end %> 

#RandomExamModel 
class RandomExam < ApplicationRecord 
    has_many :random_exam_sections, inverse_of: :random_exam 
    has_many :sections, :through => :random_exam_sections 

    accepts_nested_attributes_for :random_exam_sections, reject_if: :is_not_selected 


    private 
    def is_not_selected(attr) 
    attr["selected"] == '0' 
    end 
end 

# RandomExam 
class RandomExamSection < ApplicationRecord 
    belongs_to :random_exam 
    belongs_to :section 

    attr_accessor :selected 
end 

# Controller 
# GET /random_exams/new 
    def new 
    @random_exam = RandomExam.new 
    @random_exam.random_exam_sections.build(Section.all.map{|s| {section_id: s.id}}) 
    end 

考え方は基本的にここにトリックはビュー上で選択し、コントローラ上に構築し、検証され

- Build on controller the random_exam_sections to be selected 
- Write a form that allows to you 'select' one option and assign the number 
- Then, validate if the random_exam_section of a sections was selected (this why i made that `attr_accessor :selected`, i need a place to write if user select the exam_section) 
- If was selected, save. 

ですモデル上で選択されます。ここでは、あなたが助けを必要とする場合の例を作った:

random_exam_sectionsがすでに作成されているときにセクションを追加するには、おそらくjavascriptを使うべきです。多分これrailscastsはあなたhttp://railscasts.com/episodes/196-nested-model-form-part-1

+0

このソリューションはすばらしく、唯一の問題は、ユーザーがレコードを編集しているときでも、毎回すべてのチェックボックスを表示する必要があることです。 – Dazt

+0

こんにちは!作成時に選択ビルドを実行して、選択されていないセクションのレコードだけをビルドすることができます。これを見てください(https://github.com/afromankenobi/nested_attr_demo/blob/master/app/controllers/random_exams_controller.rb#L22)メソッドhttps://github.com/afromankenobi/nested_attr_demo/blob/master/app/コントローラ/ random_exams_controller.rb#L22 –

+0

別の回避策を使用しましたが、あなたの回答は非常に良かったです。私はそれを正解とマークします。あなたが質問に投票することができれば素晴らしいだろう、私は多くの人々がこれに苦労していると思う。あなたの時間をありがとう。 – Dazt

関連する問題