Khoga
Khoga

Reputation: 877

Rails model - insert a record - Ruby way

I am very new to Rails 4. I have created following view

contact_us.html.erb

<%= form_tag({controller: "pages", action: "contact_us"}, method: "post", class: "nifty_form") do %>
<b> Add Product </b>
<br>
  <p>
    <%= label_tag  'Cname:' %>
    <%= text_field_tag 'cname', @cname %>
    <br>
    <%= label_tag  'Cdetail:' %>
    <%= text_field_tag 'cdetais', @cdetais %>
    <% #email_field_tag 'pdetail', @pdetail %>
  </p>
  <%= submit_tag "Save" %>
<% end %>

Model : contactu.rb

class Contactu < ActiveRecord::Base
end

pages_controller.rb

class PagesController < ApplicationController
  def index
  end

  def contact_us
    flash.now[:error] = ""

    if params[:commit]
      @cname=params[:cname]
      @cdetais=params[:cdetais]

      flash.now[:error] << "Pname cannot be blank<br/>" if @cname.nil? || @cname.empty?
      flash.now[:error] << "Cdetais cannot be blank<br/>" if @cdetais.nil? || @cdetais.empty?
    end

    Contactu.create(cname: @cname, cdetais: @cdetais)
  end
end

This code works. But, I was wondering is there a better way?

I have changed the code, but now it says undefined method `join' for #

@contact_us = Contactu.create(cname: @cname, cdetais: @cdetais)

    if @contact_us.save
    flash.now[:notice] << "Information saved </br>"
    else
    flash.now[:error] = @contact_us.errors.join('<br>')
    end

Upvotes: 0

Views: 98

Answers (3)

Hauleth
Hauleth

Reputation: 23586

Of course there is better way.

Firstly check if given fields are present in model:

class Contactu < ActiveRecord::Base
  validate :cname, presence: true
  validate :cdetails, presence: true
end

And then in your controller:

@message = Contactu.create(params.permit(:cname, :cdetails))

if @message.save
  redirect_to blah, notice: "Thank's for the news"
else
  flash[:error] = @message.errors.to_a.join('<br>')
end

Upvotes: 1

bbozo
bbozo

Reputation: 7311

Indeed, see:

http://guides.rubyonrails.org/getting_started.html#saving-data-in-the-controller

but better still, RTFM, start from the beginning of the tutorial ;-)

def create
  @article = Article.new(params[:article])

  @article.save
  redirect_to @article
end

Upvotes: 0

Tom Fast
Tom Fast

Reputation: 1158

I would probably create a new controller and route to contact.

ContactController

def index
...
def create
# on success go to index

Routes:

Resources contact, only: [:index, :create]

Form: use the path helpers:

form_for **contact_path** ...

If you want the link to be a part of /pages, then that could be done as well with the routes file.

Upvotes: 0

Related Questions