T0ny lombardi February 2016

Rails4 Entering data from one controller to multiple models

I have someone of a unique problem. I have 3 tables in the database that I need to populate with data. All tables are in relation to each other. The first table's info will be static and populated from a hash. The second table is the table that is usually targeted with data.

I am having a tough time trying to add data into the second table using strong parameters. I get an error param is missing or the value is empty: entries

Modles:

client.rb

class Client < ActiveRecord::Base
  has_many :entries

end

Entry.rb

class Entry < ActiveRecord::Base
  belongs_to :client_name
  has_many :extra_data  
end

extra_data.rb

class ExtraData < ActiveRecord::Base
  belongs_to :entries
end


class ClientsController < ApplicationController

  before_action :set_client, only: [:show, :update, :destroy, :edit]

  # submit for all intended purposes.
  #
  def new
    @entries = Entry.new()
  end

  def create
    @client = Client.new(CLEINT_ATTR) 
    if @client.save
      @entries = Entry.new(submit_params)
       redirect_to action: :index
     else
       flash.alert "you failed at life for today."
        redirect_to action: :index
    end
  end

  .
  .
  .

  private

  def submit_params
    params.require(:entries).permit( :full_name,:email,:opt_in )
  end

  def set_client
    @client = Client.find(params[:id])
  end

end

form

<%= simple_form_for(:client, url: {:controller => 'clients', :action => 'create'}) do |f| %>
  <%= f.input :full_name %>
  <%= f.input :email %>
  <%= f.input :opt_in %>

  <%= f.button :submit, class: "btn-primary" %>
<% end %>

Routes:

Rails.application.routes.draw do

  resources :clients do
    resources :entries do
      resources :extra_data
    end
          

Answers


T0ny lombardi February 2016

This answer is the culmination of a few different parts.

I figured out I was not saving any data into the model. So I needed to make another if statement.

def create
  @client = Client.new(CLEINT_ATTR)
  if @client.save
    @entries = Entry.new(submit_params)
    if @entries.save
      flash[:alert] = "Failure! everything is working."
      redirect_to action: :index
    else
      flash[:alert] =  "Success! at failing."
    end
   else
     flash[:alert] =  "you failed at life for today."
      redirect_to action: :thanks
  end
end

Also changing the form from :entries Helped. I also had a typo in my permit statment. I had :opt_in when I needed to use :optin Thanks @tmc

Post Status

Asked in February 2016
Viewed 2,443 times
Voted 9
Answered 1 times

Search




Leave an answer