Rails 4 erb Ruby returns nothing - ruby-on-rails

Trying to program in ROR without scaffold. After I open the app with rails s, enter every necessary field in 'new' and enter 'show' page, 'show' gives me nothing, like this:
And here is my battles/show.html.erb:
<% provide(:title, #battle.name) %>
<h1><%= #battle.name %></h1>
<div class="">
<ul>
<li><%= #battle.name %></li>
<li><%= #battle.date %></li>
<li><%= #battle.location %></li>
<li><%= #battle.belligerentA %></li>
<li><%= #battle.belligerentB %></li>
<li><%= #battle.strengthA %></li>
<li><%= #battle.strengthB %></li>
<li><%= #battle.casualtiesA %></li>
<li><%= #battle.casualtiesB %></li>
<li><%= #battle.result %></li>
</ul>
</div>
In my battle controller, I defined show as common:
def show
#battle = Battle.find(params[:id])
end
Here is my battlecontroller:
class BattlesController < ApplicationController
def index
#battle = Battle.all
end
def new
#battle = Battle.new
end
def show
#battle = Battle.find(params[:id])
end
def create
#battle = Battle.new(battle_params)
if #battle.save
redirect_to #battle
else
render 'new'
end
end
private
def battle_params
params.require(:battle).permit(:name, :date, :location, :belligerentA, :belligerentB, :strengthA, :strengthB, :casualtiesA, :casualtiesB, :result)
end
end
When I view the page source, I cannot find any child-title h1 and li:
And Here is model:
class Battle < ActiveRecord::Base
attr_accessor :name, :date, :location, :belligerentA, :belligerentB, :strengthA, :strengthB, :casualtiesA, :casualtiesB, :result
before_save { self.name = name.downcase }
validates :name, presence: true, uniqueness: { case_sensitive: false }
validates :date, presence: true
validates :location, presence: true
validates :belligerentA, presence: true
validates :belligerentB, presence: true
validates :result, presence: true
end
Here is my rake routes result:
battles GET /battles(.:format) battles#index
POST /battles(.:format) battles#create
new_battle GET /battles/new(.:format) battles#new
edit_battle GET /battles/:id/edit(.:format) battles#edit
battle GET /battles/:id(.:format) battles#show
PATCH /battles/:id(.:format) battles#update
PUT /battles/:id(.:format) battles#update
DELETE /battles/:id(.:format) battles#destroy
root GET / pages#home
contact GET /contact(.:format) pages#contact
about GET /about(.:format) pages#about
And my new.html.erb:
<% provide(:title, 'Adding New Article') %>
<h1>Adding New Article</h1>
<div class="">
<div class="">
<%= form_for(#battle) do |f| %>
<%= render 'shared/error_messages' %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :date %>
<%= f.text_field :date %>
<%= f.label :location %>
<%= f.text_field :location %>
<%= f.label :belligerentA, 'Belligerent-A' %>
<%= f.text_field :belligerentA %>
VS
<%= f.label :belligerentB, 'Belligerent-B' %>
<%= f.text_field :belligerentB %>
<%= f.label :strengthA, 'Strength-A' %>
<%= f.text_field :strengthA %>
VS
<%= f.label :strengthB, 'Strength-B' %>
<%= f.text_field :strengthB %>
<%= f.label :casualtiesA, 'Casualties & Losses-A' %>
<%= f.text_field :casualtiesA %>
VS
<%= f.label :casualtiesA, 'Casualties & Losses-B' %>
<%= f.text_field :casualtiesB %>
<%= f.label :result %>
<%= f.text_field :result %>
<%= f.submit "Create New Article" %>
<% end %>
</div>
</div>
Could someone figure out what's going on?

Theres your problem - all the attr_accessors in the your Battle model.
Rails already provides those for you within ActiveRecord, and you've overwritten them, so your values won't be getting saved properly.
Remove them and all should be good.

Related

ActionController::InvalidAuthenticityToken When Submitting

I have a program that allows users to enter their song for a certain event. You must enter in the partycode for that event in order for it to submit. Here is a screenshot of what it looks like:
When I submit it gives me this error:
Here is what my SongsController looks like:
class SongsController < ApplicationController
def new
#song = Song.new
end
def create
current_event = Event.find(song_params[:event_id])
#song = current_event.songs.build(song_params)
if #song.save
flash[:success] = "Success"
redirect_to event_path(#song.event)
else
flash[:error] = "Failed"
end
end
def destroy
end
private
def song_params
params.require(:song).permit(:event_id, :artist, :title, :genre)
end
end
event model
class Event < ApplicationRecord
belongs_to :user
validates :name, presence: true
validates :partycode, presence: true, length: {minimum: 5}
has_many :songs, dependent: :destroy
end
song model
class Song < ApplicationRecord
belongs_to :event
validates :artist, presence: true
validates :title, presence: true
end
new.html.erb(song)
<br>
<br>
<h1> Member page </h1>
<div class ="container">
<div class="jumbotron">
<h2> Select an event to add songs to: </h2>
<%= form_for Song.new do |f| %>
<%= f.collection_select(:event_id, Event.all, :id, :name) %>
<h3> Enter your song </h3>
<%= form_for Song.new do |f| %>
<%= f.text_field :artist, placeholder: "Artist" %>
<%= f.text_field :title, placeholder: "Title" %>
<%= f.text_field :genre, placeholder: "Genre" %>
<h2> Enter the partycode for that event: </h2>
<%= form_for Event.new do |f| %>
<%= f.text_field :partycode %>
<%= f.submit "Submit", class: "btn btn-primary" %>
<% end %>
<% end %>
<% end %>
</div>
</div>
What can I do to make this functionality of my website work? Any help is greatly appreciated thanks
I see many form_for nesting on your views. It's impossible. Only one submit for a form.
I think you may want to change your _form.html.erb
<div class ="container">
<div class="jumbotron">
<h2> Select an event to add songs to: </h2>
<%= form_for #song do |f| %>
<%= f.collection_select(:event_id, Event.all, :id, :name) %>
<h3> Enter your song </h3>
<%= f.text_field :artist, placeholder: "Artist" %>
<%= f.text_field :title, placeholder: "Title" %>
<%= f.text_field :genre, placeholder: "Genre" %>
<h2> Enter the partycode for that event: </h2>
<%= f.text_field :partycode %>
<%= f.submit "Submit", class: "btn btn-primary" %>
<% end %>
</div>
</div>
You have completely messed up your form. Ideally you should have one form but here you have just kept one form within another form using form_for.
I would recommend you to have a look at the form_for documentation .

NoMethodError undefined method 'each' fir nil:NilClass

I'm facing NoMethodError in NewFormsController#create, undefined method `each' for nil:NilClass !
Here is my code :
Controller : new_forms_controller.rb
class NewFormsController < ApplicationController
def new
#form = NewForm.new
end
def create
#form = NewForm.new(params[:form])
if #form.valid?
flash[:notice] = "Successfully created recommendation."
redirect_to 'new_forms/new'
else
render :action => 'new'
end
end
end
Model : new_form.rb
class NewForm
include ActiveModel::Validations
include ActiveModel::Conversion
include ActiveModel::Naming
attr_accessor :titleID, :articleID, :content, :author
validates :titleID, :articleID, :content, :author, :presence => true
validates :titleID, :articleID => {:minimum => 5 }
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false
end
end
New View : new.html.erb
<%= content_for :title, "New Article Form" %>
<%= form_for #form do |f| %>
<% #form.errors.full_messages.each do |msg| %>
<p><%= msg %></p>
<% end %>
<p>
<%= f.label :titleID %> <br/>
<%= f.text_field :titleID %><br/>
</p>
<p>
<%= f.label :articleID %><br/>
<%= f.text_field :articleID %><br/>
</p>
<p>
<%= f.label :content %><br/>
<%= f.text_field :content %><br/>
</p>
<p>
<%= f.label :author %><br/>
<%= f.text_field :author %><br/>
</p>
<p><%= f.submit "Submit" %></p>
<% end %>
Routes : routes.rb
TestBranch::Application.routes.draw do
resources :new_forms
root :to => "new_forms#new"
end
I'm trying to implement ActiveModel because I don't want my form object to be backed up by database, I will have different service for database interactions.
You can do like this:
<% if #forms.errors.any? %>
<% #form.errors.full_messages.each do |msg| %>
<p><%= msg %></p>
<% end %>
<% end %>
Try the below code
<% if #form.errors.any? %>
<% #form.errors.full_messages.each do |msg| %>
<p><%= msg %></p>
<% end %>
<% end %>
it seems your model is correct and doens't include errors, so #form.errors contains []
you could check for errors
<% #form.errors.full_messages.each do |msg| %>
<p><%= msg %></p>
<% end unless #form.errors.blank? %>
update from my comments:
please try params[:new_form] instead of params[:form]. your identifier :form is wrong. your model called NewForm so your param name is new_form

How to save form values in database using ROR

Can anybody help me to save these form values in database.I have already created one form.When I clicked on submit button the below validation message is coming.
1 error prohibited this post from being saved:
Gender must be accepted
Please check the code and help me to save all values in DB.If any error found please make it correct.
My code is as follows:
views/students/index.html.erb
<h1>Choose the option</h1>
<p>
<%= link_to "Enter student data",students_new_path %>
</p>
<p>
<%= link_to "Display your data",students_show_path %>
</p>
views/students/new.html.erb
<h1>Enter your data</h1>
<%= form_for #student,:url => {:action => 'create'} do |f| %>
<% if #student.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#student.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% #student.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<label for="name">Name:</label>
<%= f.text_field :name,placeholder:"Enter your name" %>
</p>
<p>
<label for="gender">Gender:</label><br>
<%= f.radio_button :gender,'Male',:checked => true %>
<%= f.label :Male %>
<%= f.radio_button :gender,'Female' %>
<%= f.label :Female %>
</p>
<p>
<label for="city">Select the City</label>
<%= f.select(:city,options_for_select([['Bhubaneswar','Bhubaneswar'],['Cuttack','Cuttack'],['Behrempur','Behrempur'],['Puri','Puri']],selected: "Puri")) %>
</p>
<p>
<%= f.check_box :terms_service %> accept terms and service
</p>
<p>
<%= f.submit "Submit" %>
</p>
<% end %>
controller/students_controller.rb
class StudentsController < ApplicationController
def index
end
def show
end
def new
#student=Student.new
end
def create
#student=Student.new(users_params)
if #student.save
flash[:notice]="You have signed up successfully.."
flash[:color]="valid"
redirect_to :action => 'index'
else
flash[:notice]="You have not signed up successfully"
flash[:color]="invalid"
render :new
end
end
private
def users_params
params.require(:student).permit(:name,:gender,:city,:terms_service)
end
end
model/student.rb
class Student < ActiveRecord::Base
validates :name ,:presence => true,:length => { :minimum => 6 }
validates :gender, :acceptance => true
validates :terms_service, :acceptance => true
end
migrate\20150114061737_create_students.rb
class CreateStudents < ActiveRecord::Migration
def change
create_table :students do |t|
t.string :name
t.string :gender
t.string :city
t.string :terms_service
t.timestamps null: false
end
end
end
Please help me to run this code successfully.Thanks in advance..
Validation type used for gender field is wrong ie acceptance validation is used when you want to check if a check-box is checked by user in the form. In your situation you should use
validates :gender, :presence => true

Nested form validations not working in rails app

My validations are not working for a nested form - messages, which is in other models show page.
Here's the code:
Reserve Online:
<%= form_for([#trip, #trip.messages.build]) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.text_field :name, :class => "span3", :placeholder => "Name:" %>
<%= f.text_field :email, :class => "span3", :placeholder => "Email:" %>
<div class="h">
<%= f.text_field :subject, :class => "h", :value => (#trip.title) %>
</div>
<%= f.text_area :body, :class => "input-xlarge3", :placeholder => "Message:", :id => "textarea", :rows => "3" %>
<%= f.submit :class => " btn btn-primary btn-large ", :value => "Send Message" %>
<% end %>
</div>
Message.rb
class Message < ActiveRecord::Base
belongs_to :trip
attr_accessible :name, :email, :subject, :body
validates_presence_of :name
validates_format_of :email, :with => /^[-a-z0-9_+\.]+\#([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
validates_length_of :body, :maximum => 500
end
an the messages_controller.rb
class MessagesController < ApplicationController
def create
#trip = Trip.find(params[:trip_id])
#message = #trip.messages.create(params[:message])
if #trip.messages.create
MessageMailer.send_message(#message).deliver
redirect_to thank_you_path
else
redirect_to trip_path(#trip)
end
end
end
_error_messages.rb
<% if object.errors.any? %>
<div id="error_explanation">
<div class="alert alert-error">
The form contains <%= pluralize(object.errors.count, "error") %>.
</div>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li>* <%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
The whole code above works fine, but the validation part is simply ignored. And I don't see any errors.
So I Can't figure out what I'm doing wrong. Can You help?
Thank you!
I think there is a problem in your controller:
def create
#trip = Trip.find(params[:trip_id])
#message = #trip.messages.create(params[:message])
# the following line doesnt make sense
# you're recreating an empty message
# it should be something like "if #message.valid?"
if #trip.messages.create
MessageMailer.send_message(#message).deliver
redirect_to thank_you_path
else
redirect_to trip_path(#trip)
end
end
Try to fix that and see if it helps.

Not getting field_with_errors for some reason

I'm using Rails 3.2.2 and am not getting the field_with_errors div when the validation fails.
views/sessions/new.html.erb
<%= form_tag sessions_path do %>
<p><%= label_tag :email %><br />
<%= email_field_tag :email %></p>
<p><%= label_tag :password %><br />
<%= password_field_tag :password %></p>
<p><%= submit_tag "Log in" %></p>
<% end %>
controllers/sessions_controller.rb
def create
user = User.find_by_email(params[:email])
if user && user.authenticate(params[:password]) && user.account.subdomain == request.subdomain
session[:user_id] = user.id
redirect_to home_path
flash[:notice] = "Logged in!"
else
flash.now[:error] = "Invalid email or password"
render 'new'
end
end
models/user.rb
attr_accessible :first_name, :last_name, :email, :password, :password_confirmation
has_secure_password
validates :email, :presence => true, :uniqueness => true
validates :password, :presence => true, :on => :create
I'm getting the flash message, but my view doesn't render the field_with_errors wrapper divs if the validation fails. Any ideas?
Thanks.
It's no longer included by default, you need to render your own error messages.
Here's some sample code generated in a scaffold for a Post model:
<% if #post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% #post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
You can then extract that into a partial for re-use with your other models.
I think the field_with_errors functionality only works with form_for. If you want it, you could change your authenticate method to add errors to the the #user object (it will have to be an instance variable for this to work), and then change your form to:
<%= form_for(#user) do |f| %>
<%= f.error_messages %>
<p><%= f.label :email %><br />
<%= f.email_field :email %></p>
<p><%= f.label :password %><br />
<%= f.password_field :password %></p>
<p><%= f.submit "Log in" %></p>
<% end %>

Resources