Не удалось создать таблицу финансирования для нескольких детей - PullRequest
0 голосов
/ 24 мая 2018

каждый ребенок может подать заявку на финансирование.Но когда я подаю заявку на финансирование, он всегда создает заявку на финансирование для Child_id: 1, даже если я подаю заявку на другого ребенка.финансирование принадлежит ребенку, и дети могут иметь много средств.пожалуйста, помогите

fundings_controller.rb

def create
  @funding = Funding.new(funding_params)

  @funding.child = Child.find(child_user.ids[0])
    if @funding.save
      flash[:success] = "Thankyou for submitting"
      redirect_to funding_path(@funding)
    else 
      render 'new'
    end
end

application_controller.rb

def current_user
  @current_user ||= Family.find(session[:family_id]) if session[:family_id]
  end

  def parent_user
  @parent_user ||= Parent.find(session[:family_id]) if session[:family_id]
  end

  def child_user
    puts session[:family_id]
  @child_user ||= Child.where(:parent_id=>session[:family_id]).limit(1) if session[:family_id]
end

funding.rb

class Funding < ApplicationRecord
    has_many :organisations
    accepts_nested_attributes_for :organisations, reject_if: :all_blank, allow_destroy: true
    belongs_to :child
end

child.rb

class Child < ApplicationRecord
    belongs_to :parent
    has_many :fundings
    validates :parent_id, presence: true
    validates :firstname, presence: true
    validates :lastname, presence: true
    validates :dateofbirth, presence: true
end

parent.rb

class Parent < ApplicationRecord
    has_many :children, dependent: :destroy
    has_many :secondaryparents, dependent: :destroy
    accepts_nested_attributes_for :secondaryparents, reject_if: :all_blank, allow_destroy: true
    belongs_to :family
    validates :parent_1_firstname,   presence: true
    validates :parent_1_lastname,    presence: true
    validates :address,              presence: true
    validates :city,                 presence: true
    validates :telephone_number,     presence: true
    validates :postal_code,          presence: true
    validates :email,                presence: true
    validates :family_id,            presence: true
end

family.rb

class Family < ApplicationRecord
    has_many :parents, dependent: :destroy

    before_save { self.email = email.downcase }
    VALID_EMAIL_REGEX = /\A[A-Za-z0-9.]+@[A-Za-z0-9]+\.[A-Za-z]+\z/i
    validates :email, presence: true, uniqueness: {case_sensitive: false}, format: { with: VALID_EMAIL_REGEX }

    has_secure_password

end

Parent _form.html.erb

<%= render 'shared/errors', obj: @parent %>
<div class='row'>
  <div class= 'col-xs-12'>
    <%= form_for(@parent, :html => {class: "form-horizontal", role: "form"}) do |f| %>
        <div class = "form-group">
        <div class="control-label col-sm-2">

        <%= f.label :parent_1_firstname %>
      </div>
      <div class="col-sm-8">
        <%= f.text_field :parent_1_firstname, class: "form-control", placeholder: "Parent 1 first name", autofocus:true %>
      </div>
    </div>

       <div class = "form-group">
        <div class="control-label col-sm-2">
             <%= f.label :parent_1_lastname %>
           </div>
           <div class="col-sm-8">
             <%= f.text_field :parent_1_lastname, class: "form-control", placeholder: "Parent 1 last name", autofocus:true %>
          </div>
        </div>
        <p><strong>Add Secondary Parents or Guardians<br /></strong></p>
        <div id ='secondaryparents'>
        <%= f.fields_for :secondaryparents do |builder| %>
        <%= render 'secondaryparent_fields', :f => builder %>
        <% end %>
        <%= link_to_add_association 'Add Secondary Parent', f, :secondaryparents %>
      </div>



      <div class = "form-group">
        <div class="control-label col-sm-2">
        <%= f.label :address %>
      </div>
       <div class="col-sm-8">
        <%= f.text_area :address, class: "form-control", placeholder: "Address", autofocus:true %>
      </div>
    </div>

      <div class = "form-group">
        <div class="control-label col-sm-2">
        <%= f.label :city %>
      </div>
       <div class="col-sm-8">
        <%= f.text_field :city, class: "form-control", placeholder: "City", autofocus:true %>
      </div>
    </div>

    <div class = "form-group">
        <div class="control-label col-sm-2">
        <%= f.label :province %>
    </div>
       <div class="col-sm-8">
        <%= f.text_field :province, class: "form-control", placeholder: "Province", autofocus:true %>
      </div>
    </div>

    <div class = "form-group">
        <div class="control-label col-sm-2">
        <%= f.label :telephone_number %>
        </div>
       <div class="col-sm-8">
        <%= f.text_field :telephone_number, class: "form-control", placeholder: "Telephone Number", autofocus:true %>
    </div>
    </div>

      <div class = "form-group">
        <div class="control-label col-sm-2">
        <%= f.label :postal_code %>
        </div>
       <div class="col-sm-8">
        <%= f.text_field :postal_code, class: "form-control", placeholder: "Postal code", autofocus:true %>
      </div>
    </div>

      <div class = "form-group">
        <div class="control-label col-sm-2">
        <%= f.label :email %>
        </div>
       <div class="col-sm-8">
        <%= f.text_field :email, value: current_user.email, class: "form-control", placeholder: "Email", readonly:true, autofocus:true %>
      </div>
    </div>

      <div class = "form-group">
        <div class="control-label col-sm-2">
        <%= f.label :family_situation %>
        </div>
       <div class="col-sm-8">
        <%= f.text_area :family_situation, class: "form-control", placeholder: "Family Situation", autofocus:true %>
     </div>
    </div>
      <div class="form-group">
        <div class="col-sm-10">
        <%= f.submit class: 'btn btn-primary btn-lg' %>
      </div>
    </div>
<% end %>

</div>
</div>

children _form.html.erb

<%= render 'shared/errors', obj:@child %>

<div class='row'>
  <div class= 'col-xs-12'>
    <%= form_for(@child, :html => {class: "form-horizontal", role: "form"}) do |form| %>
        <div class = "form-group">
        <div class="control-label col-sm-2">

        <%= form.label :firstname %>
      </div>
      <div class="col-sm-8">
        <%= form.text_field :firstname, class: "form-control", placeholder: "Enter child's first name", autofocus:true %>
      </div>
    </div>
       <div class = "form-group">
        <div class="control-label col-sm-2">
             <%= form.label :lastname %>

           </div>
           <div class="col-sm-8">
             <%= form.text_field :lastname, class: "form-control", placeholder: "Enter child's last name", autofocus:true %>
          </div>
        </div>


      <div class = "form-group">
        <div class="control-label col-sm-2">
        <%= form.label :dateofbirth %>
      </div>
       <div class="col-sm-8">
        <%= form.date_field :dateofbirth, class: "form-control", placeholder: "Date of Birth", autofocus:true %>
      </div>
    </div>

      <div class = "form-group">
        <div class="control-label col-sm-2">
        <%= form.label :gender  %>
      </div>
       <div class="col-sm-8">
        <%= form.select :gender, ['Male', 'Female', 'Other'], class: "form-control", placeholder: "Gender", autofocus:true %>
      </div>
    </div> 
    <div class="form-group">
        <div class="col-sm-10">
        <%= form.submit(@child.new_record? ? "Add your child" : "Update your child ", class: 'btn btn-primary btn-lg') %>
      </div>
    </div>
  </div>
</div>
    <% end %>

финансирование _form.html.erb

<div class='row'>
  <div class= 'col-xs-12'>
    <%= form_for(@funding, :html => {class: "form-horizontal",role: "form"}) do |form| %>

      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :type_of_activity %>
        </div>
        <div class="col-sm-8">
          <%= form.select :type_of_activity, ['Swimming', 'Soccer', 'Cricket', 'Basket Ball'] %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :describe_activity %>
        </div>
          <div class="col-sm-8">
            <%= form.text_area :describe_activity %>
          </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :season %>
        </div>
        <div class="col-sm-8">
          <%= form.select :season, ['Fall', 'Winter', 'Summer'], autofocus:true %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :activity_details %>
        </div>
        <div class="col-sm-8">
          <%= form.text_area :activity_details %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :name_of_organisation %>
        </div>
        <div class="col-sm-8">
          <%= form.select :name_of_organisation, ['BCCI', 'IPL', 'Sahara', 'Not listed'], class: "form-control", autofocus:true %>
        </div>
      </div>

        <div id ='Organisations'>
        <%= form.fields_for :organisations do |builder| %>
        <%= render 'organisation_fields', :form => builder %>
        <% end %>
        <%= link_to_add_association 'Add Organisation', form, :organisations, form_name: 'form' %>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :activity_start_date %>
        </div>
        <div class="col-sm-8">
          <%= form.date_field :activity_start_date %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :number_of_weeks %>
        </div>
        <div class="col-sm-8">
          <%= form.text_field :number_of_weeks %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :days_per_week %>
        </div>
        <div class="col-sm-8">
          <%= form.text_field :days_per_week %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :hours_per_day %>
        </div>
        <div class="col-sm-8">
          <%= form.text_field :hours_per_day %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :program_registration_cost %>
        </div>
        <div class="col-sm-8">
          <%= form.text_field :program_registration_cost %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :family_contribution %>
        </div>
        <div class="col-sm-8">
          <%= form.text_field :family_contribution %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :other_funds %>
        </div>
        <div class="col-sm-8">
          <%= form.text_field :other_funds %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :other_fund_provider %>
        </div>
        <div class="col-sm-8">
          <%= form.text_field :other_fund_provider %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :amount_requested %>
        </div>
        <div class="col-sm-8">
          <%= form.text_field :amount_requested %>
        </div>
      </div> 
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :status %>
        </div>
        <div class="col-sm-8">
          <%= form.select :status, ['Pending', 'Approved', 'Declined'], class: "form-control", autofocus:true %>
        </div>
      </div> 
      <div class="form-group">
        <div class="col-sm-10">
          <%= form.submit "Apply", class: 'btn btn-primary btn-lg' %>
        </div>
      </div>
    </div>
  </div>

    <% end %>

when I create on apply for funding and then submit the form. the funding for someother child with different child_id gets created

Ответы [ 2 ]

0 голосов
/ 24 мая 2018

Поскольку родитель может подать заявку на финансирование только для одного ребенка за один раз, разрешите ему выбрать, какой ребенок в форме финансирования, и передать: child_id как часть параметров финансирования в действие FundingsController # create.

fundings_controller.rb:

def create
  @funding = Funding.new(funding_params)

  if @funding.save
    flash[:success] = "Thankyou for submitting"
    redirect_to funding_path(@funding)
  else 
    render 'new'
  end
end

application_controller.rb

def current_user
  @current_user ||= Family.find(session[:family_id]) if session[:family_id]
end

def parent_user
  @parent_user ||= Parent.find(session[:family_id]) if session[:family_id]
end

def current_children
  puts session[:family_id]
  @current_children ||= Child.where(:parent_id => parent_user.id) if session[:family_id]
end
helper_method :current_children

funding_form.html.erb

<div class='row'>
  <div class= 'col-xs-12'>
    <%= form_for(@funding, :html => {class: "form-horizontal",role: "form"}) do |form| %>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label(:child_id, "Select child") %>
        </div>
        <div class="col-sm-8">
          <%= form.select :child_id, options_for_select(current_children.map{|c| [c.firstname, c.id]}) %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :type_of_activity %>
        </div>
        <div class="col-sm-8">
          <%= form.select :type_of_activity, ['Swimming', 'Soccer', 'Cricket', 'Basket Ball'] %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :describe_activity %>
        </div>
          <div class="col-sm-8">
            <%= form.text_area :describe_activity %>
          </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :season %>
        </div>
        <div class="col-sm-8">
          <%= form.select :season, ['Fall', 'Winter', 'Summer'], autofocus:true %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :activity_details %>
        </div>
        <div class="col-sm-8">
          <%= form.text_area :activity_details %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :name_of_organisation %>
        </div>
        <div class="col-sm-8">
          <%= form.select :name_of_organisation, ['BCCI', 'IPL', 'Sahara', 'Not listed'], class: "form-control", autofocus:true %>
        </div>
      </div>

        <div id ='Organisations'>
        <%= form.fields_for :organisations do |builder| %>
        <%= render 'organisation_fields', :form => builder %>
        <% end %>
        <%= link_to_add_association 'Add Organisation', form, :organisations, form_name: 'form' %>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :activity_start_date %>
        </div>
        <div class="col-sm-8">
          <%= form.date_field :activity_start_date %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :number_of_weeks %>
        </div>
        <div class="col-sm-8">
          <%= form.text_field :number_of_weeks %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :days_per_week %>
        </div>
        <div class="col-sm-8">
          <%= form.text_field :days_per_week %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :hours_per_day %>
        </div>
        <div class="col-sm-8">
          <%= form.text_field :hours_per_day %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :program_registration_cost %>
        </div>
        <div class="col-sm-8">
          <%= form.text_field :program_registration_cost %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :family_contribution %>
        </div>
        <div class="col-sm-8">
          <%= form.text_field :family_contribution %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :other_funds %>
        </div>
        <div class="col-sm-8">
          <%= form.text_field :other_funds %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :other_fund_provider %>
        </div>
        <div class="col-sm-8">
          <%= form.text_field :other_fund_provider %>
        </div>
      </div>
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :amount_requested %>
        </div>
        <div class="col-sm-8">
          <%= form.text_field :amount_requested %>
        </div>
      </div> 
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :status %>
        </div>
        <div class="col-sm-8">
          <%= form.select :status, ['Pending', 'Approved', 'Declined'], class: "form-control", autofocus:true %>
        </div>
      </div> 
      <div class="form-group">
        <div class="col-sm-10">
          <%= form.submit "Apply", class: 'btn btn-primary btn-lg' %>
        </div>
      </div>
    </div>
  <% end %>    
</div>
0 голосов
/ 24 мая 2018

Глядя на ваши модели, это должно быть частью таблиц базы данных.

|Family |Parent    |Child      |Funding   |Organisation  |
|-------+----------+-----------+----------+--------------|
|id     | id       | id        |id        |id            |
|-------+----------+-----------+----------+--------------|
|       |family_id |parent_id  |child_id  |founding_id   |

Я вижу проблему в том, что при создании нового финансирования вы можете добавить только одного ребенка.Но вы получили коллекцию, тогда вы ограничены 1, чтобы она заработала.

Но вы добавляете только первого дочернего элемента, выбранного для current_user (.limit(1)).

Что вам нужно сделать, этодля каждого из детей, принадлежащих родителям, принадлежащим к current_user (находится в «Семье»), необходимо создать новое финансирование.

Но код сильно меняется.Удалите .limit(1), чтобы получить всю коллекцию детей, отсканируйте коллекцию и создайте финансирование для каждого ребенка.

Но я думаю, что для этого вам нужно создать новое действие в другом контроллере.

Или, но я не знаю вашей цели, рассмотрите возможность использования другой ассоциации, например has_and_belongs_to_many между Child и Funding.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...