I am able to somewhat accomplish what I am looking for, but not exactly. Saving the form when the defualt "Select a subscription" text is selected never turns out correctly. I have a form that pulls in a select from a related database:
<%= form_for [current_user, @subscription] do |f| %>
<% if @subscription.errors.any? %>
<div class="error_messages">
<h2>Form is invalid</h2>
<ul>
<% for message in @subscription.errors.full_messages %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :subscription_types, "Subscription Type" %><br />
<%= f.collection_select :subscription_type_id, @subscription_types, :id, :type_name, :prompt => "Select a subscription" %>
</p>
<p class="button"><%= f.submit %></p>
<% end %>
And I have a model that validates the the related id
class Subscription < ActiveRecord::Base
belongs_to :subscription
belongs_to :subscription_type
validates_presence_of :subscription_type_id, :on => :create, :message => "You need to select a subscription type"
end
When I try and save the form and the create action is called, the current code returns a nested array printed out to the screen. Originally, I had the "redirect_to" method set to new, but I don't think it was running the new action and establishing the variables. I set to to redirect_to in order to go through the action details, but now the errors do not set correctly. I feel that I could probably get what I need with enough tinkering, but is there a good way to pull these messages out?
class SubscriptionsController < ApplicationController
def new
puts "FAAAAAAAAAAAART-2"
@subscription = Subscription.new
@subscription_types = SubscriptionType.all
puts @subscription_types
puts "FAAAAAAAAAAAART-3"
end
def create
@subscription = Subscription.new(subscription_params)
@user = User.find(session[:user_id])
@subscription.user_id = @user.id
if @subscription.save
redirect_to root_url, :notice => "Subscription Created!"
else
puts "FAAAAAAAAAAAART-1"
flash[:error] = @subscription.errors.messages.values()
redirect_to action: :new
end
end
private
def subscription_params
params.require(:subscription).permit(:subscription_type_id)
end
end
Aucun commentaire:
Enregistrer un commentaire