I'm attempting to submit a form in Rails, and it's not creating into the db. I tried placing a binding.pry in the controller action but I'm not reaching it. Can you take a look at my form below and my controller action and let me know if I'm doing anything wrong?
<form>
<%= simple_form_for #movie do |f| %>
<div class="form-group">
<%= f.input :title, placeholder: "Movie Title", input_html: { class: 'form-control' } %>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<%= f.input :year, as: :date,
start_year: Date.today.year,
end_year: Date.today.year - 100,
discard_day: true, order: [:year],
input_html: { class: 'form-control' } %>
</div>
<div class="form-group col-md-6">
<%= f.input :genre, placeholder: "Genre", input_html: { class: 'form-control' } %>
</div>
</div>
<div class="form-group">
<%= f.input :poster, placeholder: "Poster URL", input_html: { class: 'form-control' } %>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<%= f.input :director, placeholder: "Director",
input_html: { class: 'form-control' } %>
</div>
<div class="form-group col-md-6">
<%= f.input :rating, collection: 1..5, prompt: "1(bad) - 5(great)", input_html: { class: 'form-control' } %>
</div>
</div>
<div class="form-group">
<%= f.association :lists, as: :radio_buttons, input_html: { class: 'form-control' } %>
</div>
<div class="form-group">
<%= f.input :plot, as: :text, placeholder: "Plot Summary", input_html: { class: 'form-control' } %>
</div>
<div class="form-group text-center">
<%= f.button :submit, "Add Movie", class: "btn btn-primary col-md-4"
%>
</div>
<% end %>
</form>
My controller actions:
def new
#movie = Movie.new
end
def create
binding.pry
#movie = Movie.new(movie_params)
if #movie.save
redirect_to movie_path(#movie)
else
flash[:danger] = "Please try again!"
redirect_to new_movie_path
end
end
def movie_params
params.require(:movie).permit(:title, :year, :genre, :poster, :director, :plot, :list_ids)
end
Any ideas here? The form will not submit.
You need to add rating and possibly lists into your movie_params
You can also clean your create method and make it simpler:
def create
#movie = Movie.new(movie_params)
if #movie.save
redirect_to #movie
else
flash[:danger] = "Please try again!"
render 'new'
end
end
You shouldn't need to use <form> when using simple_form.
Related
I have a parent table and in it there is a boolean field admin. I have a admin signup page where i want a hidden field for admin to set as true. Please help. I have tried the step below. please correct it as it is not working.
<div class='row'>
<div class= 'col-xs-12'>
<%= form_for(#parent, :html => { multipart: true, class: "form-horizontal", role: "form"}) do |f| %>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= f.label :email, class: "required" %>
</div>
<div class="col-sm-8">
<%= f.email_field :email, class: "form-control", placeholder: "Enter email", required: true %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= f.label :password, class: "required" %>
</div>
<div class="col-sm-8">
<%= f.password_field :password, class: "form-control", placeholder: "Enter password", required: true %>
</div>
</div>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= f.label :password_confirmation, class: "required" %>
</div>
<div class="col-sm-8">
<%= f.password_field :password_confirmation, class: "form-control", placeholder: "Re-enter password", required: true %>
</div>
</div>
<%= f.hidden_field :admin, :value => true %>
<div class="form-group">
<div class="col-sm-10">
<%= f.submit 'Sign up', class: 'btn btn-primary btn-lg' %>
</div>
</div>
<% end %>
</div>
</div>
Parent controller
def addusers
#parent=Parent.new
end
Updated parent controller
def new
#parent = Parent.new
#parent.secondaryparents.build
add_breadcrumb "Home", :root_path
add_breadcrumb "Sign up"
end
def addusers
#parent=Parent.new
end
def create_users
#parent=Parent.new(parent_params)
#parent.admin = true
if #parent.save
ParentMailer.registration_confirmation(#parent).deliver
flash[:success] = "Please ask user to confirm email address to continue"
redirect_to main_admin_path
else
flash[:danger] = "There was an error with registering. Try again"
redirect_to main_admin_path
end
end
def create
#parent = Parent.new(parent_params)
if #parent.save
ParentMailer.registration_confirmation(#parent).deliver
flash[:success] = "Please confirm your email address to continue"
redirect_to root_path(#parent)
else
flash[:danger] = "There was an error with registering. Try again"
redirect_to signup_path
end
end
Routes
resources :parents do
resources :children do
resources :fundings
end
end
end
get 'signup', to:'parents#new'
get 'login', to: 'sessions#new'
get 'usersignup', to:'parents#addusers'
post 'usersignup', to:'parents#create_users'
resources :parents, except: [:new] do
member do
get :confirm_email
end
end
Remove hidden line from html page, no need it f.hidden_field :admin, :value => true
Form_for
form_for(#parent, url: usersignup_path,
:html => { multipart: true, class: "form-horizontal", role: "form"}) do |f|
Add to routes:
post 'usersignup', to:'parents#create_users'
Controller:
def create_users
#parent = Parent.new(parent_params)
#parent.admin = true
if #parent.save
#do yr logic here
else
redirect_back(fallback_location: "/", flash: { danger: "smth went wrong.." })
end
end
def parent_params
params.require(:parent).permit(:email, :password, :password_confirmation)
end
I have two model:
1.Personne
class Personne < ApplicationRecord
has_one :proprietaire
accepts_nested_attributes_for :proprietaire
validates :nom, :prenom, :tel, :email,
presence: true
end
2 Proprietaire
class Proprietaire < ApplicationRecord
belongs_to :personne
validates :commune_id, :quartier,
presence: true
end
the Controller is:
class PersonneController < ApplicationController
def display_proprietaires
#proprietaires = Personne.all
##proprietaires = #proprietaires.proprietaire
end
def new_proprietaire
#provinces = Province.where(:parentId => nil)
#communes = Province.where.not(:parentId => nil)
#personne = Personne.new
#personne.build_proprietaire
end
def create_proprietaire
#proprietaire = Personne.new(proprietaire_params)
#proprietaire.build_proprietaire
respond_to do |format|
if #proprietaire.save
flash[:notice] = "succes"
flash[:type] = "success"
format.html { redirect_to action: :display_proprietaires }
else
flash[:notice] = "fail"
flash[:type] = "warning"
format.html { redirect_to action: :display_proprietaires }
end
end
end
def proprietaire_params
params.require(:personne).permit(:nom, :prenom, :tel, :email, proprietaire_attributes: [:id, :commune_id, :quartier]).except(:province, :commit)
end
end
the View is:
<%= form_for #personne, :url => url_for(:controller=>'personne', :action=>'create_proprietaire' ) do |f| %>
<div class="row">
<div class="col-xs-6 col-sm-6 col-lg-6">
<div class="form-group">
<%= f.label(:nom, 'Nom : ') %>
<%= f.text_field :nom, {class: "form-control", placeholder: 'Nom'} %>
</div>
<div class="form-group">
<%= f.label(:prenom, 'Prenom : ')%>
<%= f.text_field :prenom, {class: "form-control", placeholder: "Prenom"} %>
</div>
<div class="form-group">
<%= f.label(:tel, 'Telephone : ')%>
<%= f.text_field :tel, {class: "form-control", placeholder: "Telephone"} %>
</div>
<div class="form-group">
<%= f.label(:email, 'Email : ') %>
<%= f.text_field :email, {class: "form-control", placeholder: "Email"} %>
</div>
<div class="form-group">
<%= label_tag(:province, 'Province : ') %>
<%= select_tag(:province, options_for_select(#provinces.collect{|value| [value.denomination, value.id]}), {class: "form-control", id: "province", remote: true} ) %>
</div>
<%= f.fields_for :proprietaire do |proprio| %>
<div class="form-group">
<%= proprio.label(:commune_id, 'Commune : ') %>
<%= proprio.select :commune_id, options_for_select(#communes.collect{|value| [value.denomination, value.id]}),{}, {class: "form-control", id: "commune"} %>
</div>
<div class="form-group">
<%= proprio.label :quartier, "Quartier" %>
<%= proprio.text_field :quartier, {class: "form-control", placeholder: "Quartier"} %>
</div>
<% end %>
<%= f.submit "Enregistre", {class: 'btn btn-info'} %>
<% end %>
Routes:
resources :personne do
collection do
post :create_proprietaire
get :display_proprietaires
get :new_proprietaire
end
end
I'm new in RoR, When I try to save nothing happens, I'm getting this:
Could someone helps me on this. Thank you!
You have your association set to required but it's missing.
Associations are set to required by default in rails 5 so if you want to keep one empty you need to set optional:true on your association in model
I am trying to use the fields_for helper method on a project I am working on. The original form works and saves just fine. The new attributes do not save and I get a NoMethodError and a undefined method. What am I missing?!
Here is my listing model:
class Listing < ActiveRecord::Base
has_one :listing_commerical_attribute
accepts_nested_attributes_for :listing_commerical_attribute, :allow_destroy => true
Here is my listing_commercial_attribute model:
class ListingCommercialAttribute < ActiveRecord::Base
belongs_to :listing
accepts_nested_attributes_for :listing
end
Here is my controller:
def new
#listing.build_listing_commercial_attribute
respond_to do |format|
format.html # new.html.erb
format.json { render json: #listing }
end
end
private
def commercial_params
params.require(:commerical_listing_attribute)
.permit(:gas_pipe_size,
:amperage,
:basement_ceiling_height,
:ceiling_height,
:door_size,
:zoning,
:previous_use,
:community_board,
:delivery_date,
:key_money,
:security_deposit,
:price_per_sq_ft,
:did_size)
end
Here is my _form.html.erb:
<h2 class="text-center">Commercial</h2>
<%= f.fields_for :listing_commerical_attributes do |ff| %>
<div class="field">
<%= ff.label :gas_pipe_size, "Gas Pipe Size", class: "general-text-label" %>
<%= ff.number_field :gas_pipe_size, class: "general-text-field" %>
</div>
<div class="field">
<%= ff.label :amperage, "Amperage", class: "general-text-label" %>
<%= ff.number_field :amperage, class: "general-text-field" %>
</div>
<div class="field">
<%= ff.label :ceiling_height, "Ceiling Height", class: "general-text-label" %>
<%= ff.number_field :ceiling_height, class: "general-text-field" %>
</div>
<div class="field">
<%= ff.label :basement_ceiling_height, "Basement Ceiling Height", class: "general-text-label" %>
<%= ff.number_field :basement_ceiling_height, class: "general-text-field" %>
</div>
<div class="field">
<%= ff.label :door_size, "Door Size", class: "general-text-label" %>
<%= ff.number_field :door_size, class: "general-text-field" %>
</div>
<div class="field">
<%= ff.label :zoning, "Zoning", class: "general-text-label" %>
<%= ff.text_field :zoning, class: "general-text-field" %>
</div>
<div class="field">
<label for="tenant_improvements" class="general-text-label">Tenant Improvements <small>(If Applicable)</small></label>
<%= ff.text_area :tenant_improvements, :rows => "4", class: "general-text-area" %>
</div>
<div class="field">
<label for="previous_use" class="general-text-label">Previous Use <small>(If Applicable)</small></label>
<%= ff.text_area :previous_use, :rows => "4", class: "general-text-area" %>
</div>
<div class= "field">
<%= ff.label :community_board, "Community Board", class: "general-text-label" %>
<%= ff.text_field :community_board, class: "general-text-field" %>
</div>
<div class="field">
<%= ff.label :delivery_date, "Delivery Date", class: "general-text-label" %>
<div class="input-group">
<span class="input-group-addon"><i class="nklyn-icon-calendar"></i></span>
<%= ff.text_field :delivery_date, :class => "datepicker general-text-field" %>
</div>
<div class="field">
<%= ff.label :key_money, "Key Money", class: "general-text-label" %>
<div class="input-group">
<span class="input-group-addon"><i class="nklyn-icon-money-bills"></i></span>
<%= f.text_field :key_money, class: "general-text-field", value: number_with_precision(f.object.price, delimiter: ',', precision: 0) %>
</div>
</div>
<div class="field">
<%= ff.label :security_deposit, "Security Deposit", class: "general-text-label" %>
<div class="input-group">
<span class="input-group-addon"><i class="nklyn-icon-money-bills"></i></span>
<%= f.text_field :security_deposit, class: "general-text-field", value: number_with_precision(f.object.price, delimiter: ',', precision: 0) %>
</div>
</div>
<div class="field">
<%= ff.label :price_per_sq_ft, "Price Per Sq Ft", class: "general-text-label" %>
<div class="input-group">
<span class="input-group-addon"><i class="nklyn-icon-money-bills"></i></span>
<%= f.text_field :price_per_sq_ft, class: "general-text-field", value: number_with_precision(f.object.price, delimiter: ',', precision: 0) %>
</div>
</div>
<div class="field">
<%= ff.label :did_size, "Drive In Doors Size", class: "general-text-label" %>
<%= ff.number_field :did_size, class: "general-text-field" %>
</div>
<% end %>
Update
I made the change to the ListingCommercialAttribute model and removed the accepts nested attributes for.
I changed the f.fields_for to singular instead of plural.
I added in the nested attributes after the parent (see below)
def listing_params
params.require(:listing)
.permit(:access,
:address,
:apartment,
:cats_ok,
:cross_streets,
:dogs_ok,
:latitude,
:longitude,
:amenities,
:date_available,
:bathrooms,
:bedrooms,
:description,
:fee,
:exclusive,
:featured,
:rental,
:residential,
:landlord_contact,
:listing_agent_id,
:sales_agent_id,
:neighborhood_id,
:pets,
:photo,
:photo_tag,
:primaryphoto,
:price,
:square_feet,
:station,
:status,
:subway_line,
:term,
:title,
:utilities,
:move_in_cost,
:owner_pays,
:private,
:office_id,
:full_address,
:zip,
:convertible,
:landlord_llc,
:pinned,
:image,
listing_commercial_attribute_attributes: [
:gas_pipe_size,
:amperage,
:basement_ceiling_height,
:ceiling_height,
:door_size,
:zoning,
:previous_use,
:community_board,
:delivery_date,
:key_money,
:security_deposit,
:price_per_sq_ft,
:did_size])
end
Here are my new controller actions:
def edit
#listing.attributes = listing_params
end
def create
#listing.attributes = listing_params
respond_to do |format|
if #listing.save
format.html { redirect_to #listing, notice: 'Listing was successfully created.' }
format.json { render json: #listing, status: :created, location: #listing }
else
format.html { render action: "new", notice: "Correct the mistakes below to create the new listing" }
format.json { render json: #listing.errors, status: :unprocessable_entity }
end
end
end
But now I am getting a NoMethodError in Listings#show error. I created a partial for the commercial attributes. Shouldn't they be included now that they are in the strong params, or am I totally misunderstanding that?!
Here is the partial:
Gas Pipe Size: <%= listing_commercial_attributes.gas_pipe_size(#listing) %>
Amperage: <%= listing_commercial_attribute.amperage(#listing) %>
Basement Ceiling Height: <%= listing_commercial_attribute.basement_celing_height(#listing) %>
Ceiling Height: <%= listing_commercial_attribute.ceiling_height(#listing) %>
Door Size: <%= listing_commercial_attribute.door_size(#listing) %>
Zoning: <%= listing_commercial_attribute.zoning(#listing) %>
Build to Suit: <%= listing_commercial_attribute.build_to_suit(#listing) %>
Previous Use: <%= listing_commercial_attribute.previous_use(#listing) %>
Community Board: <%= listing_commercial_attribute.community_board(#listing) %>
Delivery Date: <%= listing_commercial_attribute.delivery_date(#listing) %>
Key Money: <%= listing_commercial_attribute.key_money(#listing) %>
Update #2
I changed it to singular.
Here is the complete error.
NameError in Listings#show
Showing /Users/Code/app/views/listings/_commercial_attributes.html.erb where line #1 raised:
undefined local variable or method `listing_commercial_attribute' for #<#:0x007f86606f6a10>
Did you mean? listing_collection_url
Gas Pipe Size: <%= listing_commercial_attribute.gas_pipe_size(#listing) %>
Amperage: <%= listing_commercial_attribute.amperage(#listing) %>
Basement Ceiling Height: <%= listing_commercial_attribute.basement_celing_height(#listing) %>
Ceiling Height: <%= listing_commercial_attribute.ceiling_height(#listing) %>
Door Size: <%= listing_commercial_attribute.door_size(#listing) %>
Zoning: <%= listing_commercial_attribute.zoning(#listing) %>
Trace of template inclusion: app/views/listings/_listing_content_area.html.erb, app/views/listings/show.html.erb
Update #3
def show
#my_listing_collections = ListingCollection.with_agent(current_agent).order("created_at DESC")
#listing_commercial_attributes = ListingCommercialAttribute.find(params[:id])
#regions = Region.order(name: :asc)
#listing = Listing.includes(:photos, :likes, :interested_agents).find(params[:id])
if #listing.private && cannot?(:create, Listing)
redirect_to listings_path, notice: 'This listing is no longer available'
else
agent = Agent.where(id: params[:agent_id]).first
#page = Listings::ShowView.new(#listing, agent)
respond_to do |format|
format.html
end
end
end
I keep getting this error:
ActiveRecord::RecordNotFound in ListingsController#show
Couldn't find ListingCommercialAttribute with 'id'=5755
It is searching for the commercial attribute with an id of 5755, but that is the listing id. I'm not sure what to pass in there...
Do not define accepts_nested_attributes_for on both models. Only on the parent model. Otherwise you'll run into circular dependency issues. In this case the parent model looks like it's a Listing, so remove accepts_nested_attributes_for :listing from ListingCommercialAttribute.
The first argument to f.fields_for should be the name of the association and yours is slightly off. You have has_one : listing_commerical_attribute so you want f.fields_for : listing_commerical_attribute.
The Strong Parameters should require your parent object first and include nested objects second. Also, you must append _attributes to the end of your nested attribute name.
So, for 3:
def listing_params
params.require(:listing)
.permit(:id,
# ...
listing_commercial_attribute_attributes: [ # Note: _attributes
:gas_pipe_size,
# ...
])
end
In the create/edit actions, be sure to set the params from the strong parameters method: #listing.attributes = listing_params.
Read more in the docs on accepts_nested_attributes_for and Strong Parameters.
I have 2 models.
Scoreboard Model : can have many teams
Team Model : belongs to Scoreboard
Teams has the follow columns:
name: string
win,loss,tie: integer
On the Team#Index view, I have a collection of all the teams associated to the Scoreboard. Also on that page, I can render an edit form on top of each team object and update it through ajax. Here is the relevant code:
Team#Index View:
<div class="team-list">
<%= render #teams.reject(&:new_record?) %>
</div>
_team.html.erb
<div class="row team-div" id="team_<%=team.id%>">
<%= link_to (scoreboard_team_path(#scoreboard, team)) do %>
<div class="col-xs-4 team-div-1"> <%= team.name %> </div>
<% end %>
<%= link_to (edit_scoreboard_team_path(#scoreboard, team)), remote: true, class: "team-edit-link" do %>
<div class="col-xs-6 team-data">
<div class="row">
<div class="col-xs-4 team-div-2"><%= team.win %> </div>
<div class="col-xs-4 team-div-2"><%= team.loss %> </div>
<div class="col-xs-4 team-div-2"><%= team.tie %></div>
</div>
</div>
<% end %>
</div>
As you can see, I have an edit link available which renders an edit form in place of the team object in question through ajax. The edit form only updates the win,loss,tie columns.
Edit form rendered:
<%= form_for [#scoreboard, #team], remote: true do |f| %>
<div class="row team-edit-form">
<div class="col-xs-4 edit-team-1">Placeholder</div>
<div class="col-xs-2 edit-team-2"><%= f.number_field :win, min: 0, max: 9999, class: "form-control", placeholder: "0" %></div>
<div class="col-xs-2 edit-team-2"><%= f.number_field :loss, min: 0, max: 9999, class: "form-control", placeholder: "0" %></div>
<div class="col-xs-2 edit-team-2"><%= f.number_field :tie, min: 0, max: 9999, class: "form-control", placeholder: "0" %></div>
<div class="col-xs-2 edit-team-3"> <%= f.submit "Done", :data => {:disable_with => "Saving..."}, class: "btn btn-primary" %></div>
</div>
<% end %>
Team#update Controller Method(which by ajax reloads the newly edited team object div):
def update
#scoreboard = Scoreboard.find(params[:scoreboard_id])
#team = #scoreboard.teams.find(params[:id])
if #team.update_attributes(team_params)
respond_to do |format|
format.html {redirect_to scoreboard_teams_path(#scoreboard)}
format.js
end
else
respond_to do |format|
format.html {redirect_to scoreboard_teams_path(#scoreboard)}
format.js { render action: "update_error" }
end
end
end
Now for my problem. All the above happens on the team#index view by ajax.
On the team#show view, I would like to edit only the team name without ajax.
So far, this is what the team#show view looks like:
Team#show View
<h3> <%= #team.name %> <h3>
<%= form_for [#scoreboard, #team] do |f| %>
<div class="col-xs-4"><%= f.text_field :name, required: true, maxlength: 30, class: "team-name-field form-control", placeholder: "Enter name" %></div>
<div class="col-xs-1"> <%= f.submit "Update", :data => {:disable_with => "Saving..."}, class: "btn btn-primary" %></div>
<% end %>
Upon submission, I would like to update the name and then redirect the page back to the team#show(no ajax required). Currently, this form also routes to the same update method. Is it possible to use the same update method but execute different response code for the team#show view? If not, how can I have a customized update code executed when I submit the form on the team#show page?
I'm not sure you can use a different respond_to as you can only redirect or render once in an action.
One approach would be to create a new route / controller method for updating the team name.
routes
resources :teams do
member { post 'update_name' }
end
show.html.erb
In the view, you can post to the above route and in the controller, create a method for the new route.
<%= form_for #team, :url => update_name_team_path(#team)
teams_controller
def update_name
#team = Team.find(params[:id])
redirect_to team_path(#team)
end
Yes, you can do this by checking the request type or sending a flag/keyword to check for the response to render, I would do it like :
Add hidden_field for request param in edit form like :
<%= form_for [#scoreboard, #team], remote: true do |f| %>
<div class="row team-edit-form">
<div class="col-xs-4 edit-team-1">Placeholder</div>
<div class="col-xs-2 edit-team-2"><%= f.number_field :win, min: 0, max: 9999, class: "form-control", placeholder: "0" %>
<%= f.hidden_field :request, 'js' %> </div>
<div class="col-xs-2 edit-team-2"><%= f.number_field :loss, min: 0, max: 9999, class: "form-control", placeholder: "0" %></div>
<div class="col-xs-2 edit-team-2"><%= f.number_field :tie, min: 0, max: 9999, class: "form-control", placeholder: "0" %></div>
<div class="col-xs-2 edit-team-3"> <%= f.submit "Done", :data => {:disable_with => "Saving..."}, class: "btn btn-primary" %></div>
</div>
<% end %>
Add hidden_field for request param in name edit form in show page like :
<%= form_for [#scoreboard, #team] do |f| %>
<div class="col-xs-4"><%= f.text_field :name, required: true, maxlength: 30, class: "team-name-field form-control", placeholder: "Enter name" %>
<%= f.hidden_field :request, 'http' %> </div>
<div class="col-xs-1"> <%= f.submit "Update", :data => {:disable_with => "Saving..."}, class: "btn btn-primary" %></div>
<% end %>
Team#Update Method will be like :
def update
#scoreboard = Scoreboard.find(params[:scoreboard_id])
#team = #scoreboard.teams.find(params[:id])
if #team.update_attributes(team_params)
redirect_to scoreboard_teams_path(#scoreboard) if params[:request] == 'http'
render "" if params[:request] == 'js'
else
redirect_to scoreboard_teams_path(#scoreboard) if params[:request] == 'http'
render action: "update_error" if params[:request] == 'js'
end
end
I'm following this tutorial to set up Devise integration with Stripe: http://www.jaredrader.com/blog/2013/12/18/a-stripe-integration
I have successfully setup Stripe as detailed and created the various controllers, models and views.
However, the forms are creating an ArgumentError in Users::Registrations#new
Here's the error code:
ArgumentError in Users::Registrations#new
Showing /home/action/workspace/mediadb/app/views/devise/registrations/new.html.erb where line #62 raised:
First argument in form cannot contain nil or be empty
The form:
<div class="panel panel-default">
<div class="panel-heading">
<% if params[:plan] == "2" %>
<h1>Sign up with premium!</h1>
</div>
<div class="panel-body">
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<%= hidden_field_tag 'plan', params[:plan] %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, autofocus: true, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :email %>
<%= f.email_field :email, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :password %>
<%= f.password_field :password, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation, class: "form-control" %>
</div>
<h2>Payment</h2>
<%= f.hidden_field :stripe_card_token %>
<div class="form-group">
<%= label_tag :card_number, "Credit Card Number" %>
<%= text_field_tag :card_number, nil, name: nil, class: "form-control" %>
</div>
<div class="form-group">
<%= label_tag :card_code, "Security Code on Card (CVV)" %>
<%= text_field_tag :card_code, nil, name: nil, class: "form-control" %>
</div>
<div class="form-group">
<%= label_tag :card_month, "Card Expiration" %>
<%= select_month nil, {add_month_numbers: true}, {name: nil, id: "card_month"}%>
<%= select_year nil, {start_year: Date.today.year, end_year: Date.today.year+15}, {name: nil, id: "card_year"}%>
</div>
<div id="stripe_error">
<noscript>JavaScript is not enabled and is required for this form. First enable it in your web browser settings.</noscript>
</div>
<div class="form-group">
<%= f.submit "Sign up", class: "btn btn-lg btn-success" %>
</div>
<% end %>
</div>
<% else %>
<h1>Sign up for free</h1>
</div>
<div class="panel-body">
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), html: { id: "free_plan"}) do |f| %>
<%= devise_error_messages! %>
<%= hidden_field_tag 'plan', params[:plan] %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, autofocus: true, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :email %>
<%= f.email_field :email, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :password %>
<%= f.password_field :password, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation, class: "form-control" %>
</div>
<div class="form-group">
<%= f.submit "Sign up", class: "btn btn-lg btn-primary" %>
</div>
<% end %>
<% end %>
</div>
</div>
The routes.rb file:
Rails.application.routes.draw do
resources :lists
resources :publications
resources :contacts
devise_for :users, controllers: { registrations: 'users/registrations' }
devise_scope :user do
get '/sign_up', to: 'users/registrations#new', as: :sign_up
get '/sign_in', to: 'devise/sessions#new', as: :sign_in
get '/:id/edit', to: 'users/registrations#edit', as: :edit
put 'users/update_plan', :to => 'users/registrations#update_plan'
put 'users/cancel_plan', :to => 'users/registrations#cancel_plan'
end
resources :users, only: [:index, :show]
# root should always be last
root to: 'pages#home'
end
The Registration controller:
class Users::RegistrationsController < Devise::RegistrationsController
def new
unless (params[:plan] == '1' || params[:plan] == '2')
flash[:notice] = "Please select a plan to sign up."
redirect_to root_url
end
end
def update_plan
#user = current_user
#user.update_attributes(plan_id: params[:plan], email: params[:email], stripe_card_token: params[:user][:stripe_card_token])
if #user.plan_id == 2
#user.save_with_payment
redirect_to edit_user_registration_path, notice: "Updated to premium!"
else
flash[:error] = "Unable to update plan."
render :edit
end
end
def cancel_plan
#user = current_user
if #user.cancel_user_plan(params[:customer])
#user.update_attributes(stripe_customer_token: nil, plan_id: 1)
flash[:notice] = "Canceled subscription."
redirect_to edit_user_registration_path
else
flash[:error] = "There was an error canceling your subscription. Please notify us."
render :edit
end
end
private
def build_resource(*args)
super
if params[:plan]
resource.plan_id = params[:plan]
if resource.plan_id == 2
resource.save_with_payment
else
resource.save
end
end
end
def setup
plans = Plan.all
plans.each do |plan|
unless plan.id == 1
#startup_plan = plan
end
end
end
end
Any idea what's wrong?
Update Users::RegistrationsController#new as follows
def new
if (params[:plan] == '1' || params[:plan] == '2')
super
else
flash[:notice] = "Please select a plan to sign up."
redirect_to root_url
end
end