How do I add form errors for a model that belongs to another model, rails 3.1 - ruby-on-rails-3.1

I'm following along with the Rails Guides - Getting Started tutorial. It makes a basic Post model, and a Comment model that belongs to Post.
I have added a simple validation to the Comment model, and it works, but I can't figure out how to get form errors to display if I fill it out wrong.
Here is my comment.rb model
class Comment < ActiveRecord::Base
validates :body, presence: true
belongs_to :post
end
Here is the original form for adding a comment, it's in posts/show.html.erb
<h2>Add a comment:</h2>
<%= form_for([#post, #post.comments.build]) do |f| %>
<div class="field">
<%= f.label :commenter %><br />
<%= f.text_field :commenter %>
</div>
<div class="field">
<%= f.label :body %><br />
<%= f.text_area :body %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
And the original create action in comments_controller.rb
class CommentsController < ApplicationController
def create
#post = Post.find(params[:post_id])
#comment = #post.comments.create(params[:comment])
redirect_to post_path(#post)
end
end
I've tried quite a few things, but it all feels like fumbling around in the dark. Can someone point me in the right direction please?

Take a look at the dynamic_form gem - this used to be part of Rail itself but was extracted a while back. With it, you can display errors inline like this:
<%= f.label :commenter %><br />
<%= f.text_field :commenter %>
<%= f.error_message_on :commenter %>

Related

l18n::InvalidLocaleData Rails

Error occurs when you click on a url http://localhost:3000/articles/new/.
Showing c:/Sites/blog/app/views/articles/new.html.erb where line #8 raised:
can not load translations from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/activesupport-4.1.8/lib/active_support/locale/en.yml: expects it to return a hash, but does not
File blog.html.erp
<h1>New article</h1>
<%= form_for :article do |f| %>
<p>
<%= f.label :title%><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text%><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
Controller articles action new.
class ArticlesController < ApplicationController
def new
end
end
File config/routes.rb
Rails.application.routes.draw do
resource :articles
get 'welcome/index'
Rails 4.1.8
Ruby 2.1.5
Winddows 7
Delete all of the files C:\RailsInstaller\Ruby2.1.0\lib\ruby\gems\2.1.0\gems\activesupport-4.1.8\lib\active_support\locale\en.yml put - en:

How to solve ParameterMissing error using ROR

Please help me to solve the below error.
Error:
ActionController::ParameterMissing in CustmersController#create
param is missing or the value is empty: users
When i am submitting the data,this error is coming.
My code is as follows
views/custmers/new.html.erb
<h1>Enter your data here</h1>
<center>
<%= form_for #users,:url => {:action => 'create'} do |f| %>
<% if #users.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#users.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% #users.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",:class => "input-field" %>
</p>
<p>
<label for="email">Email:</label>
<%= f.email_field :email,placeholder:"Enter your email",:class => "input-field" %>
</p>
<p>
<label for="phone">Phone no:</label>
<%= f.telephone_field :phoneno,placeholder:"Enter your phone number",:class => "input-field" %>
</p>
<p>
<%= f.submit "Submit" %>
</p>
<% end %>
<%= link_to "BACK",custmers_index_path %>
</center>
controller/custmers_controller.rb
class CustmersController < ApplicationController
def index
end
def new
#users=Custmer.new
end
def show
end
def create
#users=Custmer.new(user_params)
if #users.save
flash[:notice]="You have signed up successpully"
flash[:color]="valid"
redirect_to :action => 'index'
else
flash[:alert]="You have not signed up successfully"
flash[:color]="invalid"
render :new
end
end
private
def user_params
params.require(:users).permit(:name,:email,:phoneno)
end
end
model/custmer.rb
class Custmer < ActiveRecord::Base
EMAIL_REGEX = /\A[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\z/i
validates :name,presence:true,length: { minimum: 5 }
validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX
validates :phoneno, presence: true,length: {minimum: 10}
end
I am using rails version-4.2.0 and ruby version-1.9.3.Please help me to resolve this error.
If you look at the stack trace accompanying your error, you could tell definitely where the problem is -- look for the first line in the stack trace that refers to your code (and not library code).
But a fair guess is the require(:users) line in your controller. It looks like you either copy/pasted this code from another controller, or changed the name of your controller after generating it as part of your scaffold.
It should be requires(:custmer) instead, as that is the class of the thing you're submitting.
As a general approach, you should follow the standard Rails practices for naming things, throughout. If you really want to use the misspelled, Custmer class, have at it, but use #custmr inside your controller and views to refer to an instance, not #users.

Getting undefined method `klass' for nil:nilclass - Railscast #197

Hi all I followed Ryan Bates' railscasts on nested models and form, but I am getting getting undefined method `klass' for nil:nilclass. I am pretty sure it is due to the the link_to_add_fields since everything was working prior. Below is my error and other relevant code and I'm using Rails 3.1. I did a lot of googling and did not find any to solve my problem, so if you guys could help me out I would really appreciated it. Thanks for your help.
_form.html.erb
<%= form_for(#organization) do |f| %>
<% if #organization.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#organization.errors.count, "error") %> prohibited this organization from being saved:</h2>
<ul>
<% #organization.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 id="restaurant_field" class="field">
<%= f.fields_for :restaurants do |builder| %>
<%= render 'organizations/partials/restaurant_fields', :f => builder %>
<% end %>
</div>
<div class="actions"><%= f.submit %></div>
<% end %>
_restaurant_fields.html.erb
<p class="fields">
<%= f.label :name, "Restaurant Name" %><br />
<%= f.text_field :name %>
<%= link_to_remove_fields "Remove", f %>
application_helper.rb
module ApplicationHelper
def link_to_remove_fields(name, f)
f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)")
end
def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render(association.to_s.singularize + "_fields", :f => builder)
end
link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))
end
end
application.js
function remove_fields(link) {
$(link).prev("input[type=hidden]").val("1");
$(link).closest(".fields").hide();
}
function add_fields(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g");
$(link).parent().before(content.replace(regexp, new_id));
}
I found that the link_to_add_fields helper won't work if the associated model is describe by a has_one. The has_one means the association does not get the klass object.
You can determine this is your problem by changing your relationship to has_many :object + s (your object name with an s) and passing your object in plural to link_to_add_fields.
You have done the same thing as this person here
Edit: (error on my part)
I am assuming you have an link_to_add_fields below this line
<%= link_to_remove_fields "Remove", f %>
as it seems that the _restaurant_fields.html.erb partial is incomplete. (no closing tag)
</p>
Remove the link_to_add_fields outside of the f.fields_for
That should solve the klass error.

Rails 3 Nested Form not being created

The models I'm working with look like this:
class ComplexAssertion < ActiveRecord::Base
has_many :expression_groups
has_many :expressions, :through => :expression_group
accepts_nested_attributes_for :expression_groups, :allow_destroy=>true
end
class ExpressionGroup < ActiveRecord::Base
belongs_to :complex_assertion
has_many :expressions
accepts_nested_attributes_for :expressions, :allow_destroy=>true
end
class Expression < ActiveRecord::Base
belongs_to :expression_group
end
My form looks like the following:
<%= form_for(#complex_assertion) do |f| %>
<div id="mainAssertionGroup" style="border:1px; border-style:solid; width:1000px; padding:5px">
<div class="field">
<%= f.label :title %>: <%= f.text_field :title, :size=>'10' %>
<%= f.label :description %>: <%= f.text_field :description, :size=>'25' %>
<%= f.label :scope %>: <%= f.text_field :scope, :size=>'1' %>
Test
Category: <%= collection_select(:complex_assertion, :assertion_category_id, AssertionCategory.all, :id, :name, {:include_blank=>"UNCATEGORIZED"}) %>
</div>
<div id="initialGroup" style="border:1px; margin-left:10px; margin-top:10px; border-style:solid; width:850px;">
<div class="childGroup1" style="padding:5px;">
<%= f.fields_for :expression_groups do |eg| %>
<%= eg.fields_for :expressions do |e| %>
Type: <%= e.collection_select :assertion_type_id, AssertionType.all, :id, :name %>
Attribute: <%= e.collection_select :attribute_name, Attribute.find_by_sql("select distinct a.name from attributes a "), :name, :name %>
<%= e.label :operator_type_id %>
: <%= e.collection_select :operator_type_id, OperatorType.all, :id, :value %>
Value: <%= e.text_field :value, :size=>'1' %>
<% end %>
<div id="innerOperator">
<%= eg.collection_select :logical_operator_type_id, LogicalOperatorType.all, :id, :value %>
</div>
<% end %>
</div>
</div>
</div>
<div id="createComplex" align="center">
<%= f.submit :value=>'Submit' %>
</div>
<% end %>
And my controller looks like:
def new_complex_assertion
#complex_assertion = ComplexAssertion.new
end
When I load the page, I only the ComplexAssertion portion of the form and get nothing back for the ExpressionGroups or the Expressions. It's as if there isn't anything available. But, if you see my controller, I did a ComplexAssertion.new which I though would create the dependent objects automagically; I assume I'm incorrect?
I'm debugging through RubyMine and when I evaluate the ComplexAssertion.new, I only see 5 attributes, the five that are defined for only that object, none of the relational objects. What am I doing incorrectly?
EDIT
Looks like if I do the following:
#complex_assertion = ComplexAssertion.new
#complex_assertion.expression_groups.build
#complex_assertion.expressions.build
And change my form to use:
<%= f.fields_for :expressions do |e| %>
instead of eg.fields_for, it shows the forms.
This DOES NOT give me the correct nesting. I thought I should be able to do:
#complex_assertion.expression_groups.expressions.build
but it tells me that expressions is an undefined method.
Yes, you have to explicitly instantiate the associated objects. It is not done for you.
#complex_assertion.expression_groups.expressions.build
Will not work because expression_groups is an array and not an individual expression group. So, after you create the expressions_groups do the following:
#complex_assertion.expressions_groups.each do |group|
group.expressions.build
end
Also, you could replace the 2nd line with the following as well to create multiple expressions
2.times do { group.expressions.build }
As for using fields_for with nested models, make your code in the form look like this:
<%= f.fields_for :expression_groups, #complex_assertions.expression groups do |eg| %>
<%= eg.fields_for :expressions, eg.object.expressions do |e| %>
I will try to explain what is going on. The :expressions_groups is telling fields_for what class of object it is going to render fields for, and the second part I added is telling fields_for where to find the object(s) to render fields for. If we are passing in an array, which we are in this case, it will automatically iterate over the array. On each iteration, it puts the current model object we are working with into a variable called object which is stored in the form builder instance returned by fields_for. So we use this to tell the second fields_for where to find the expression model objects it needed. This means eg.object points to an expression_group model object.
I hope this helps and makes sense. Also, I have not tested anything and am only pointing out what looks out of place.

Rails 3 Render / Partial

I'm very new to Rails 3 and I've followed some tutorials and now I'm trying to "play" with the code created. I have followed the tutorial from http://guides.rubyonrails.org/getting_started.html
I'm am trying to render the form for new posts on the homepage with this code:
<%= render :partial => "posts/form" %>
The posts/_form.html.erb looks like this:
<%= form_for(#post) do |f| %>
<% 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 %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :content %><br />
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
and this is the error I get:
undefined method `model_name' for NilClass:Class
Extracted source (around line #1):
1: <%= form_for(#post) do |f| %>
2: <% if #post.errors.any? %>
3: <div id="error_explanation">
4: <h2><%= pluralize(#post.errors.count, "error") %> prohibited this post from being saved:</h2>
Trace of template inclusion: app/views/home/index.html.erb
Rails.root: d:/server/cazare
Application Trace | Framework Trace | Full Trace
app/views/posts/_form.html.erb:1:in `_app_views_posts__form_html_erb___794893824_70478136_519766'
app/views/home/index.html.erb:5:in `_app_views_home_index_html_erb__967672939_70487520_0'
I understand that this may seem a piece of cake for some of you but I'm trying to understand how everything works on Rails so I hope you can understand me.
Thanks in advance !
#post variable is not instantiated in the Controller :)
so "#post = Post.new" inside the controller action should do the trick
Rails is attempting to build a form for the object #post. In order to do that, it needs to know what sort of object #post is; that way, it can find any existing data in the object and fill it into the form for you. Rails has a method grafted on to objects called model_name to do the lookup, but it won't be grafted onto NilClass (the class of the nil object).
I suspect that you haven't defined #post anywhere - it's an instance variable of the Controller, so you'd expect the controller to either find #post from the database, or to call #post = Post.new - so it's nil.
In the posts/_form.html.erb,
change
<%= form_for(#post) do |f| %>
to
<%= form_for(Post.new) do |f| %>

Resources