stergosz
stergosz

Reputation: 5860

ruby on rails custom function validate and post

I have create a controller named Invites and a model named invite and i have created a new function in the controller named request_invite which i want to use for users to enter their email address, validate it and that it does not exist in the invites table and then post it to the database

invites_controller.rb

class InvitesController < ApplicationController

    def request_invite
        render_404 unless request.xhr?

        @email = params[:get_invited_email]

        if @email
            flash[:notice] = "msg + insert"
        else
            flash[:notice] = "msg"
        end

    end

end

invite.rb

class Invite < ActiveRecord::Base

end

i have not added resources in the routes file

form

<%= form_tag(invite_request_path, :method => "post", :id => "landing_request_invite_form") do %>
    <%= text_field_tag 'get_invited_email', nil, :placeholder => 'Enter your email address' %>
    <%= submit_tag 'Get Invited', :id => "get_invited_btn" %>
<% end %>

javascript

  $("#landing_request_invite_form").submit(function(e){
    e.preventDefault();
    var form = $(this);
    var url = form.attr("action");
    var formData = form.serialize(); 
    $.post(url, formData, function(html) { 
        console.log('request done');
    });
    return false;
  });

how can i check that the email does not exist? do i use the .find() method?

Upvotes: 1

Views: 328

Answers (1)

Erez Rabih
Erez Rabih

Reputation: 15788

I will assume in my answer that Invite model has an invited_email column in the DB.

class Invite < ActiveRecord::Base
  validates :invited_email, :uniqueness => true
end

class InvitesController < ApplicationController
    def request_invite
        render_404 unless request.xhr?

        @invitation = Invite.new(params[:invite])
        if @invitation.save
            flash[:notice] = "msg + insert"
        else
            flash[:notice] = "msg"
        end
    end
end

<%= form_for Invite.new, :url => invite_request_path, :id => "landing_request_invite_form" do |f| %>
    <%= f.text_field :invited_email, :placeholder => 'Enter your email address' %>
    <%= f.submit 'Get Invited', :id => "get_invited_btn" %>
<% end %>

Brief explanation:

@invitation.save goes through validation and returns false if the object is invalid and since we put validates :invited_email, :uniqueness => true in our Invite model it won't be valid if an Invite with same invited_email value already exists.

I would also like to advise you to change request_invite action to create action. I see no reason not to - what you are doing is exactly creation of a new invitation. If you do that you may omit the :url => invite_request_path from the from builder since rails goes to the create action by default when the form object is a new instance (like Invite.new)

Upvotes: 2

Related Questions