user3754535
user3754535

Reputation: 131

Inserting data to a model from a custom controller Rails

I created a scaffold for a model called "Charge", but I want to insert data to the model from a custom controller I created "Checkout".

I have the following code:

#in the routes.rb
get "checkout/pay", to: 'checkout#index'

#in the app/controllers/checkout_controller.rb
 def index
   @charge = Charge.new
 end

#in the app/views/checkout/index.html.erb

<%= form_for(@charge, url: charges_path, method: :post ) do |f| %>


  <% if @charge.errors.any? %>
    <div id="error_explanation">
  <h2><%= pluralize(@charge.errors.count, "error") %> prohibited this charge from being saved:</h2>

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

  <div class="title">
    <h1>shipment</h1>
  </div>

  <div class="large-12 columns">
    <%= f.text_field :name, placeholder: "name", maxlength: "20", class: "radius" %>
  </div>
  <div class="large-12 columns">
    <%= f.text_field :address, placeholder: "address", class: "radius" %>
  </div>
  <div class="large-12 columns">
    <%= f.text_field :email, placeholder: "email", class: "radius" %>
  </div>
  <hr>


  <%= f.submit "buy", class: "button green radius small expand" %>
 <% end %>


#in the app/controllers/charges_controller.rb

 def create
   @charge = Charge.new(id: "523dd8f6aef8784386000001", amount: 60000, livemode: false, created_at: 1379784950, status: "paid", currency: "MXN", description: "Pizza", reference_id: "9839-wolf_pack", failure_code: "none", failure_message: "none", name: params[:name], address: params[:address], email: params[:email], ship_number: "5678sdf7sd5f6")
   @charge.save
   respond_with(@charge)
 end

#in the app/models/charge.rb
 validates :name, :address, :email, presence: true

Just for testing I filled some data with default values in the create method. In the form ('/checkout/pay') I filled :name, :address, :email, manually with data, but redirect me to the new_charge_path and tells me: Name can't be blank Address can't be blank Email can't be blank

There is some error with trying to get the params from the form in the html view?

Upvotes: 1

Views: 900

Answers (1)

Alfonso
Alfonso

Reputation: 759

You are using form_for view helper, according to rails conventions, the controller gets a nested hash params[:charg] with the charge attributes set in the form.

So, on your controller you must call:

@charge = Charge.new(name: params[:charge][:name], address: params[:charge][:address], email: params[:charge][:email])

Upvotes: 4

Related Questions