Rhys0h
Rhys0h

Reputation: 351

Save to database from outside model

I have a website with two models: blog_posts and subscribers. They do not inherit from each other. When visitors are browsing through the different blog posts, I'd like them to have the option to add themselves to my subscriber database via a form partway down the page.

This is what I'd like to have on my /blog_posts page:

<%= form_for :subscriber do |f|  %>
    <%= f.label :name, "Name" %>
    <%= f.text_field :name %>
    <%= f.label :name, "Email" %>
    <%= f.text_field :email %>
    <%= f.submit "SUBSCRIBE!" %>
<% end %>

It doesn't make sense to associate blog_posts with subscribers. Is what I'm trying to do possible?

Upvotes: 0

Views: 27

Answers (1)

Eyeslandic
Eyeslandic

Reputation: 14900

You can just use a regular form

<%= form_for Subscriber.new do |f|  %>
  ...
<% end %>

and handle it in the regular way in a SubscriberController

class SubscriberController < ApplicationController
   def create
     Subscriber.create(safe_params[:subscriber])
     redirect_to thank_you_path
   end

   def safe_params
     params.require(:subscriber).permit(:name, :email)
   end
end

Upvotes: 1

Related Questions