validations failing as blank when fields not blank - validation

I am runnning ruby 1.9.3 and rails 4.1.4
trying the following validations
in the models\profile.rb
attr_accessor :password
validates :name, :presence => true, :uniqueness => true, :length => { :in => 3..20 }
validates :password, :confirmation => true #password_confirmation attr
validates_length_of :password, :in => 6..20, :on => :create
before_save :encrypt_password
in view profiles\new.html.erb
from the form
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<p>
<%= f.label :email %><br />
<%= f.text_field :email %>
</p>
<p>
<%= f.label :password %><br />
<%= f.password_field :password %>
</p>
<p>
<%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %>
</p>
<p>
<%= f.label :interests %><br />
<%= f.text_area :interests %>
</p>
<p>
<%= f.label :zip %><br />
<%= f.text_field :zip %>
</p>
<p>
<%= f.label :country %><br />
<%= f.country_select :country, ["United Kingdom"] %> </p>
using strong parameters controllers\profile_controller,rb
class ProfilesController < ApplicationController
def new
#profile = Profile.new
end
def create
#profile = Profile.new(params[profile_params])
if #profile.save
flash[:notice] = "You signed up successfully"
flash[:color]= "valid"
else
flash[:notice] = "Form is invalid"
flash[:color]= "invalid"
end
render "new"
end
private
## Strong Parameters
def profile_params
params.require(:profile).permit(:name, :email, :password, :interests,:zip)
end
end
validations always fail saying fields are blank. By causing an exception the report shows model profile with its fields populated. It is as if the data is simply not accessible so I suspect I'm misuing strong parameters sonehow.
Any opinions welcomed.

The profile_params function is going to return a hash for you with the data directly.
What that basically does is it filters the params hash for the 'profile' key's value for the keys named as the parameters of permit(...)
So the way to fix is to write
#profile = Profile.new(profile_params)
instead of
#profile = Profile.new(params[profile_params])
With strong parameters you almost never interact with the params array directly from controller actions (such as create). The private strong parameter methods will handle that for you and by that, only safe, filtered data will be given to your controller actions.

Related

Adding Categories In Rails 3

I am building an uploader for videos and giving the videos a category through categorizations. Every time I try to upload a video I receive an error saying
NameError in VideosController#create
uninitialized constant Video::Categorization
I want to able to add one category to each video. But no regardless of how I write the association I get the same error.
model
class Video < ActiveRecord::Base
attr_accessible :source, :title, :url, :description,
:category, :category_id, :category_list
belongs_to :user
has_many :category, through: :categorizations
has_many :categorizations
validates :category, presence: true
has_attached_file :source
def source_remote_url=(url_value)
self.source = URI.parse(url_value) unless url_value.blank?
super
end
def self.categorized_with(name)
Category.find_by_name!(name).videos
end
def category_list
["Action", "Anime",
"Arts and Culture", "Beauty", "Business", "Comedy",
"Documentary", "Drama",
"Food", "Gaming", "Health and Fitness", "Horror"]
end
def category_list=(names)
self.category = names.split(",").map do |n|
Category.where(name: n.strip).first_or_create!
end
end
end
Video Controller
class VideosController < ApplicationController
before_filter :authenticate_user!
before_filter :set_video, only: [:show, :edit, :update, :destroy]
respond_to :html
def index
#videos = Video.all
end
def show
respond_with(#video)
end
def new
#video = Video.new
respond_with(#video)
end
def edit
end
def create
#video = Video.new(params[:video])
#video.save
respond_with(#video)
end
def update
#video.update_attributes(params[:video])
respond_with(#video)
end
def destroy
#video.destroy
respond_with(#video)
end
private
def set_video
#video = Video.find(params[:id])
end
end
Form
<%= form_for(#video) do |f| %>
<% if #video.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#video.errors.count, "error") %> prohibited this video from being saved:</h2>
<ul>
<% #video.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 :source %><br />
<%= f.file_field :source %>
</div>
<div class="field">
<%= f.label "Category", class: 'control-label' %>
<%#= f.select :category, Category.all, :prompt => 'Select One' %>
<%= f.select :category_list, video_category, :prompt => "Select a category..." %>
</div>
<div class="field">
<%= f.label :description %><br />
<%= f.text_area :description, rows: 4, placeholder: "Description" %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
If you declare
has_many :category, through: :categorizations
it should be
has_many :categories, through: :categorizations

Add font awesome icons to a form label

Is it possible to use font awesome icons within a label when creating a form for example.
if my form looks like this
<%= f.label :email %>
<%= f.email_field :email, :autofocus => true %>
How would i add the i class to the label?
I have tried this
<%= f.label :email, :class => 'icon-user' %>
<%= f.email_field :email, :autofocus => true %>
but this doesn't work?
Try something like this (assuming email is a field of class User):
<%= f.label :email do %>
<i class="icon-user"></i>
<%= User.human_attribute_name :email %>
<%- end -%>

how to do a many to many model for this project in rails

I'm having trouble creating a many to many model for my project.
Basically i have a Matches & Teams model.
Teams are created prior to the Matches.
Once the match is created then i would like to add teams to it.
Match can have many teams, Teams can have many matches.
I'm currently adding teams via nested_form and adding multiple teams at once.
When submitting the form, i get an error expecting the team to be in a relationship already with the match.
I can do this with a many to one relationship but it fails with many-to-many, was wondering if there was any way to do it without doing a custom route.
Below is the form, controllers are as per default values.
Form:
<%= nested_form_for(#match) do |f| %>
<% if #match.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#match.errors.count, "error") %> prohibited this match from being saved:</h2>
<ul>
<% #match.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :date %><br />
<%= f.date_select :date %>
</div>
<%= f.fields_for :teams, :html => { :class => 'form-vertical' } do |builder| %>
<%= builder.label "Team Name:" %>
<%= builder.autocomplete_field :name, autocomplete_team_name_teams_path, :update_elements => {:id => "##{form_tag_id(builder.object_name, :id)}" },:class => "input-small",:placeholder => "Search" %>
<%= builder.hidden_field :id %>
<% end %>
<%= f.link_to_add raw('<i class="icon-plus-sign"></i>'), :teams, :class => 'btn btn-small btn-primary' %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Using a join model, the has_many :through macro and the accepts_nested_attributes_for macro you can do something like the following.
class Match
has_many :competitions
has_many :teams, :through => :competitions
accepts_nested_attributes_for :teams
end
class Competition
belongs_to :match
belongs_to :team
end
class Team
has_many :competitions
has_many :matches, :through => :competitions
end
Just make sure your form is set up to send the following data structure as params when the request reaches the create or update controller.
params => {
:match => {
# ...
:teams_attributes => [
{ :name => 'Foo', :color => 'blue' },
{ :name => 'Bar', :color => 'green' },
# ...
]
}
}

Rails 3.1 nested form issue

Ive got the following scenario:
cmsasset model that is container for image using paperclip to upload and store, location model that can have attached cmsassets in a habtm join table approach
location accepts nested attributes for cmsassets here's the exact model code:
accepts_nested_attributes_for :cmsassets, :allow_destroy => true
now when i try to use the following in my form code the nested form is not displayed:
<%= form_for #location do |f| %>
<%= render 'shared/error_messages', :target => #location %>
<p>Name<br />
<%= f.text_field :name %></p>
<p>Description<br />
<%= f.text_area :description %></p>
<p>Location Tags (Separated by a Comma)<br />
<%= f.text_field :tag_names %></p>
<%= render :partial => 'shared/contact_info_form', :locals => {:f => f} %>
<p>Splash Image:<br />
<%= f.fields_for :cmsassets do |cmsasset_form| %>
<%= cmsasset_form.number_field :client_id, :type => 'hidden', :value => session[:current_client] %>
<p>Image Name:<br />
<%= cmsasset_form.text_field :name %></p>
<p>Description:<br />
<%= cmsasset_form.text_field :description %></p>
<p><%= cmsasset_form.file_field :attachment %><br />
<%= cmsasset_form.text_field :cms_asset_type, :type => 'hidden', :value => 'Splash' %></p>
<% end %></p>
<p>Display Address:<br />
<%= f.text_field :display_addr %></p>
<p>Latitude<br />
<%= f.number_field :latitude %></p>
<p>Longitude<br />
<%= f.number_field :longitude %></p>
<p>Trigger Radius<br />
<%= f.number_field :trigger_radius%></p>
<p>Published >> <%= f.check_box :published %></p>
<p>Expiration Date<br />
<%= f.text_field :expiration_date %></p>
<br />
<%= f.submit "Save" %>
However, when I make cmsassets singular in the nested form call it renders but fails obviously because of the habtm data structure...
whats crazy is that this approach works using the nested_form gem, with the sole exception of paperclip causing a failure in this case because we use dynamic styles at the model level..
if anyone can shed some light on either of these issues i'd be very interested to hear some ideas!
It's not valid HTML to write nested forms.
Try to place the upload form outside the main form.

Rails Save File Checkbox

How can I make it so that my info only gets stored if the checkbox is checked. Here is what I have so far:
<% #extra.each do |extra| %>
<%= f.fields_for :purchaseds do |builder| %>
<div class="label-field">
<%= builder.label :name, extra.name %>
<p><%= extra.description %></p>
</div>
<div class="text-field">
$<%= extra.price %>
<%= builder.check_box :purchased %>
</div>
#I WOULD LIKE THIS TO ONLY GET SAVED IF THE CHECK BOX FOR PURCHASED IS CHECKED
<%= builder.hidden_field :name, :value => extra.name %>
<%= builder.hidden_field :description, :value => extra.description %>
<%= builder.hidden_field :price, :value => extra.price %>
<% end %>
<% end %>
My client asked to be able to add extra services himself, and then users could be able to choose if they want to purchase them as accessories to their order. So what I did was I made a table called Extra (for extra services) and another table called Purchased. Purchased belongs to Order and is a nested attribute.
In your purchaseds model add validations:
validates_presence_of :name, :description, :price, :if => :purchased
Update
Add :reject_if option to your purchaseds parent model in
accepts_nested_attributes_for :purchaseds, :reject_if => {|attrs| !attrs[:purchased]}

Resources