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
Related
So although I have used cocoon successfully before, I'm still relatively new and for whatever reason can't seem to get it to pass through the parameters (I've tried with two different applications and on fedora 22 and mac 10.10.4).
For context I've been using the standard rails forms in .erb and have both :post and :post_items which only currently have a description. I'm using cocoon 1.2.6.
So in application.js I have
//= require cocoon
in post.rb
class Post < ActiveRecord::Base
has_many :post_items
accepts_nested_attributes_for :post_items, :reject_if => :all_blank, :allow_destroy => true
validates :title, :post_items, presence: true
validates :title, length: {maximum: 255}
end
in post_item.rb
class PostItem < ActiveRecord::Base
belongs_to :post
end
and my relevant controllers are (posts_controller.rb):
def index
#post = Post.new
end
def create
params[:post][:ip_address] = request.remote_ip
#post = Post.create(post_params)
if #post.save
flash[:success] = "Your post was successfully created"
redirect_to #post
else
flash[:failure] = "There was an error saving your post"
render 'index'
end
end
private
def find_post
#post = Post.find(params[:id])
end
def post_params
params.require(:post).permit(:title, :tags, :hits, :ip_address, post_items_attributes: [:id, :description, :_destroy])
end
And finally in my views I have (_form.html.erb)
<%= form_for #post, html: {multipart: true} do |f| %>
<% if #post.errors.any? %>
<p>There were <%= #post.errors.count %> errors</p>
<% #post.errors.full_messages.each do |msg| %>
<p><%= msg %></p>
<% end %>
<% end %>
<!-- a bunch of fields here -->
<div class="six columns">
<h3>Add images</h3>
<div id="post_items">
<% f.fields_for :post_items do |post_item| %>
<%= render 'post_item_fields', f: post_item %>
<% end %>
<div class="links">
<%= link_to_add_association 'Add Image', f, :post_items, class: "add-button" %>
</div>
</div>
<%= f.button :submit, class: "button submit-button" %>
<% end %>
and lastly _post_item_fields.html.erb
<div class="nested-fields">
<div class="field">
<%= f.label :description %>
<%= f.text_area :description %>
</div>
<%= link_to_remove_association "Remove", f %>
</div>
There are CSS files that modify the html but I have no js other than what's automatically built. I've literally been stuck on this problem for days now and I can't figure out what's wrong. I have tried the post.rb without the validates code but it still doesn't work.
The only lead I have is that when you print out the parameters it has already dropped the post_items parameters and for the life of me I can't figure out why.
Thanks for the help!
EDIT: for the sake of information I've added my migrations.
in db/migrate/20150722191917_create_post_items.rb
class CreatePostItems < ActiveRecord::Migration
def change
create_table :post_items do |t|
t.string :description
t.belongs_to :post, index: true, foreign_key: true
end
end
end
and in db/migrate/20150722173629_create_posts.rb
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :title
t.string :tags
t.integer :hits, null: false, default: 0
t.string :ip_address
t.timestamps null: false
end
add_index :posts, :ip_address
end
end
Also if it matters I didn't use scaffold when generating them
Well I think I finally figured out what's wrong (although I don't really understand what we're supposed to do to get around it) is that once I got rid of div class="six columns" it worked, so apparently that was interfering with the cocoon gems ability to parse the html.
Thanks everyone for all the help!
EDIT: to clarify I had to change _form.html.erb to:
<%= form_for #post, html: {multipart: true} do |f| %>
<% if #post.errors.any? %>
<p>There were <%= #post.errors.count %> errors</p>
<% #post.errors.full_messages.each do |msg| %>
<p><%= msg %></p>
<% end %>
<% end %>
<!-- a bunch of fields here -->
<h3>Add images</h3>
<div id="post_items">
<% f.fields_for :post_items do |post_item| %>
<%= render 'post_item_fields', f: post_item %>
<% end %>
<div class="links">
<%= link_to_add_association 'Add Image', f, :post_items, class: "add-button" %>
</div>
</div>
<%= f.button :submit, class: "button submit-button" %>
<% end %>
So I guess it was a little my fault as the error would have been easier to spot if I had used the full html instead of parsing it for the cocoon-relevant bits but there it is regardless. (basically the moral of this story is that you can't have div's inside of the form)
I have a Word model and a Category model.
Words has_and_belongs_to_many Categories.
Categories has_and_belongs_to_many Words.
Now, I have everything setup and running in the console, for example you can do:
Word.create(title: "Testicles")
testicles = Word.first
Category.create(title: "Genitalia")
genitalia = Category.first
testicles.categories << genitalia
testicles.categories
=> "genitalia"
Now I can get this up and running using forms in the views too, but only if I have separately created the Category in its own form on a separate page, and same with the Word. Then in the Word show view I can create a form to assign the category to it.
HOWEVER... what I really want to do is to do all this at the same time when I create the Word i.e. on the 'new word' view.
I'm having big problems working out how to do this. I think I'm right in saying that I can only have one form and one submit in that view, so I think I somehow have to send everything from that form to, say, the WordsController, and work some magic in there, but exactly what to do here is giving me big headaches. Can anyone help?
I haven't created a User model or setup authentication yet, so there are no obstacles in that respect.
models/word.rb:
class Word < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :categories
validates :title, presence: true
end
models/category.rb:
class Category < ActiveRecord::Base
has_and_belongs_to_many :words
validates :title, presence: true
end
schema.rb:
ActiveRecord::Schema.define(version: 20150529144121) do
create_table "categories", force: :cascade do |t|
t.string "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "categories_words", id: false, force: :cascade do |t|
t.integer "category_id"
t.integer "word_id"
end
add_index "categories_words", ["category_id"], name: "index_categories_words_on_category_id"
add_index "categories_words", ["word_id"], name: "index_categories_words_on_word_id"
create_table "words", force: :cascade do |t|
t.string "title"
t.text "description"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "words", ["user_id"], name: "index_words_on_user_id"
end
After experimenting with various form_tag wizardry (and failing badly), at the moment I'm using this form:
<%= form_for(#word) do |f| %>
<% if #word.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#word.errors.count, "error") %> prohibited this word from being saved:</h2>
<ul>
<% #word.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title, 'Word' %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :description, 'Definition' %><br>
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.label :categories, 'Category' %><br>
<%= f.text_field :categories %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
In the view, the form has:
#<Category::ActiveRecord_Associations_CollectionProxy:0x007f16dd834820>
in the 'Category' box, but this can be cleared and your own category inputted. When submitting the form with all the fields filled in, I get a NoMethodError.
So basically you want to create both a word and a category at the same time, and link them. If the classical solutions (for example using the nested_form gem) don't do exactly what you want, you can try this approach.
You really want a custom view/controller for this and do the business in your controller as you suggest. I suggest that instead you used a simple form_tag where you can add some fieldsets.
View
<%= form_tag your_custom_route_path, :html => {:class => "form-horizontal"} do |form| %>
<%= fields_for :word, #word do |f| %>
<%= f.text_field :title %>
<% end %>
<%= fields_for :category, #category do |f| %>
<%= f.text_field :title %>
<% end %>
<% end %>
routes
post '/yourRoute', to: 'your_controller#your_action_create', as: 'your_custom_route'
Controller featuring some actions
class YourController < ApplicationController
# new
def your_action_new
#word = Word.new
#category = Category.new
end
# Post
def your_action_create
#word = Word.new(word_params)
#category = Category.new(category_params)
if #word.save and #category.save
#word.categories << #category
#word.save
end
end
private
def words_params
params.require(:word).permit(:title, ...)
end
def category_params
params.require(:category).permit(:title...)
end
Thanks to Cyril DD's help, I've expanded on that and created a form and custom controller that will create a new Word with a new Category assigned to it and/or the user can assign existing Categories to that new Word.
_form.html.erb:
<%= form_tag(controller: "new_word", action: "create_word_and_category", method: "post") do %>
<% if #word.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#word.errors.count, "error") %> prohibited this category from being saved:</h2>
<ul>
<% #word.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= fields_for :word, #word do |word_form| %>
<div class="field">
<%= word_form.label(:title, "Word:") %><br>
<%= word_form.text_field(:title, id: "new_word", required: true) %>
</div>
<div class="field">
<%= word_form.label(:description, "Definition:") %><br>
<%= word_form.text_area(:description) %>
</div>
<% end %>
<%= fields_for :category, #category do |category_form| %>
<% if Category.count > 0 %>
<div class="field">
<%= category_form.label(:title, "Choose from existing Categories:") %><br>
<%= category_form.collection_check_boxes(:category_ids, Category.all, :id, :title) %>
</div>
<% end %>
<h4>AND/OR...</h4>
<div class="field">
<%= category_form.label(:title, "Create and Use a New Category:") %><br>
<%= category_form.text_field(:title) %>
</div>
<% end %>
<div class="actions">
<%= submit_tag("Create") %>
</div>
<% end %>
new_word_controller.rb (it's not completely finished yet, but it 'does what it says on the tin'):
class NewWordController < ApplicationController
def create_word_and_category
#word = Word.new(word_params)
if #word.save
(params["category"])["category_ids"].each do |i|
next if i.to_i == 0
#word.categories << Category.find(i.to_i) unless #word.categories.include?(Category.find(i.to_i))
end
if category_params.include?(:title) && ((params["category"])["title"]) != ""
#word.categories << Category.new(title: (params["category"])["title"])
end
end
if #word.save
redirect_to words_path, notice: 'Word was successfully created.'
else
redirect_to new_word_path, notice: 'A valid word was not submitted.'
end
end
private
# Use callbacks to share common setup or constraints between actions.
# def set_word
# #word = Word.find(params[:id])
# end
# Never trust parameters from the scary internet, only allow the white list through.
def word_params
params.require(:word).permit(:title, :description, :user_id)
end
def category_params
params.require(:category).permit(:title, :category_ids, :category_id)
end
end
In my routes.rb:
post 'create_word_and_category' => 'new_word#create_word_and_category'
I'm having going to place that controller code into the old words_controller, because I don't see a need to have it in a separate controller like this. If anyone has any thoughts/critique, great. And if anyone can help me write an rspec controller test for this controller code, even better! I'm having trouble with that.
My Rails App consists of touristic Routes. Each route has many stops and waypoints and stops have categories.
Waypoints are just the intermediate model between routes and stops because stops can belong to many routes.
So, when i try to save a Stop, i get the error:
undefined method `category' for #<Stop:0x007fa067acea90>
And the " if #stop.save" line is highlighted in red:
respond_to do |format|
if #stop.save
Waypoint.create(route_id: params[:route_id] , stop_id: #stop.id)
#print out category id or name here
category = params[:category]
In my stops controller i have this on create:
def create
#stop = Stop.new(stop_params)
respond_to do |format|
if #stop.save
Waypoint.create(route_id: params[:route_id] , stop_id: #stop.id)
#print out category id or name here
category = params[:category]
#once printed save it (stop category)
StopCategory.create(category_id: category, stop_id: #stop.id)
format.html { redirect_to #stop, notice: 'Stop was successfully created.' }
format.json { render :show, status: :created, location:#stop }
else
format.html { render :new }
format.json { render json: #stop.errors, status: :unprocessable_entity }
end
end
And on my waypoints controller i have this on create:
def create
#waypoint = Waypoint.create(waypoint_params)
redirect_to #waypoint.route
end
This is the stop model:
class Stop < ActiveRecord::Base
validates :description, length: { maximum: 140 }
validates :category, presence: true
#Image Uploader
mount_uploader :stop_image, StopImageUploader
#Relationship with stops and waypoints
has_many :waypoints
has_many :routes, through: :waypoints
# Relationship with categories
has_many :stop_categories
has_many :categories, through: :stop_categories
end
And this is the view where the form is :
<h2>Create a new stop:</h2><br>
<%= form_for(#stop) do |f| %>
<% if #stop.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#stop.errors.count, "error") %> prohibited this stop from being saved:</h2>
<ul>
<% #stop.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<select name="category" id=" " >
<option value="" disabled selected> Select a Category </option>
<% #categories.each do |category| %>
<option value="<%= category.id %>"> <%= category.name %> </option>
<% end %>
</select>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.label :stop_image %><br>
<%= f.file_field :stop_image %>
</div>
<div class="field">
<%= f.label :stop_lat %><br>
<%= f.number_field :stop_lat, :class => 'text_field', :step => 'any' %>
</div>
<div class="field">
<%= f.label :stop_long %><br>
<%= f.number_field :stop_long, :class => 'text_field', :step => 'any' %>
</div>
<%= hidden_field_tag :route_id, params[:id] %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<h2>Add existing stop</h2>
<br>
<%= form_for(#waypoint) do |f| %>
<div class="field">
<%= f.label :stop_id %><br>
<%= f.number_field :stop_id %>
</div>
<%= f.hidden_field :route_id %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<%= link_to 'Edit', edit_route_path(#route) %> |
<%= link_to 'Back', routes_path %>
<br>
<br>
<br>
</div>
Any ideas ?
Thanks!
Do you have a 'category' attribute in your Stop model? If not, then the following doesn't make sense:
validates :category, presence: true
That is where it's probably failing.
If you want to validate the presence of categories, you need to replace that check with something like this:
validate :has_categories
def has_categories # make this private
if categories.blank?
# add errors here
end
end
The following might also work:
validates :categories, presence: true
In the Stop model, you should replace the line
validates :category, presence: true
with
validates :categories, presence: true
because the validator takes the attribute/association name as argument, not the model name of the association.
Your association is called categories, so that's what you need to perform the validation on.
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.
I have a Rails 4 application and just installed the Paperclip gem to handle image uploading. I can't get it working, after I've uploaded a photo it just says missing.
Someone has a clue what's going wrong?
~settings/_form.html.erb
> <%= form_for(#setting, :html => { :multipart => true }) do |f| %>
> <% if #setting.errors.any? %>
> <div id="error_explanation">
> <h2><%= pluralize(#setting.errors.count, "error") %> prohibited this setting from being saved:</h2>
>
> <ul>
> <% #setting.errors.full_messages.each do |msg| %>
> <li><%= msg %></li>
> <% end %>
> </ul>
> </div>
> <% end %>
>
> <div class="field">
> <%= f.label :title %><br>
> <%= f.text_field :title %>
> </div>
> <div class="field">
> <%= f.label :description %><br>
> <%= f.text_area :description %>
> </div>
> <div class="field">
> <%= f.label :paragraph %><br>
> <%= f.text_area :paragraph %>
> </div>
> <div>
> <%= f.file_field :photo %>
> </div>
> <div class="actions">
> <%= f.submit %>
> </div>
> <% end %>
My setting model ~setting.rb
class Setting < ActiveRecord::Base
attr_accessible :title, :description, :paragraph
has_attached_file :photo
end
Photo Migration
class AddAttachmentPhotoToSettings < ActiveRecord::Migration
def self.up
change_table :settings do |t|
t.attachment :photo
end
end
def self.down
drop_attached_file :settings, :photo
end
end
Setting migration
class CreateSettings < ActiveRecord::Migration
def change
create_table :settings do |t|
t.string :title
t.text :description
t.text :paragraph
t.timestamps
end
end
end
~settings/Show.html.erb
<p id="notice"><%= notice %></p>
<p> <%= image_tag #setting.photo.url %> </p> <br />
<p>
<strong>Title:</strong>
<%= #setting.title %>
</p>
<p>
<strong>Description:</strong>
<%= #setting.description %>
</p>
<p>
<strong>Paragraph:</strong>
<%= #setting.paragraph %>
</p>
<%= link_to 'Edit', edit_setting_path(#setting) %> |
<%= link_to 'Back', settings_path %>
Can't figure out what's wrong. The uploaded photo does'nt show it just says "Missing". Would appreciate some help! :)
You can keep the first one : setting_params. It seems to be a method in your controller to ensure strong parameters (see: http://guides.rubyonrails.org/getting_started.html#saving-data-in-the-controller).
To resolve it, add the relation in this method like this :
private
def setting_params
params.require(:post).permit(:title, :description, :paragraph, :photo)
end
I'm glad to tell everyone that have or will have the same problem that I just figured it out!
By default your generated controller that you want to add the :photo attribute to defines "create" like this:
def create
#setting = Setting.new(setting_params)
end
Just cange it to:
def create
#setting = Setting.create(params[:setting])
end
(Just to be clear; Change setting to your own scaffold name.)