Rails Form In General Layout - ruby-on-rails-3

I'm know this is a newbie question just not sure what I'm missing and decided to post hear after my usual search through Google. I'm trying to post content to the database from a form in the footer of the application (for a newsletter) the view is therefore repeated throughout the application. Right now when I submit the form a new object is created in the database but all the fields are "NULL". It seems I need to put the #newsletter variable somewhere, I'm just not sure where.
Partial I'm Rendering in the View
<%= form_tag({:controller => "newsletters", :action => "create"}, :method => "post", :id => "footer_email_form") do %>
<%= text_field_tag :first_name, '', id: "footer_email_firstname" %>
<%= text_field_tag :last_name, '', id: 'footer_email_lastname' %>
<%= text_field_tag :email, '', id: 'footer_email_address' %>
<%= submit_tag "Submit", :name => nil, id: 'footer_email_submit', class: "btn btn-primary" %>
<% end %>
Controller (Create Action)
class NewslettersController < ApplicationController
def create
#newsletter = Newsletter.new(params[:newsletter])
if #newsletter.save
format.html { redirect_to 'pages#home', notice: 'Thank You for signing up for our newsletter' }
format.json { render json: #newsletter, status: :created, location: #newsletter }
else
format.json { render json: #newsletter.errors, status: :unprocessable_entity }
end
end
end
Routes
resources :newsletters, :only => [:create, :destroy]

Use something like this:
<%= form_for Newsletter.new do |f| %>
<%= f.text_field :first_name %>
<%= f.text_field :last_name %>
<%= f.text_field :email %>
<%= f.submit_tag "Submit", class: "btn btn-primary" %>
<% end %>
The way your original form works the params are submitted like this:
params = {
:first_name => 'A',
:last_name => 'B',
:email => 'C',
# and so on...
}
Now if you do #newsletter = Newsletter.new(params[:newsletter]) nothing will happen, because params[:newsletter] is nil and therefore all your attributes are going to be nil (and show up as NULL in the DB).
You should always have an eye on the development log. It's going to help you debug such errors.

Related

undefined method `model_name' in a partial rendered by different controller

I'm trying to render this form:
<form class="form-inline">
<%= simple_form_for #prospect,
:url => url_for(:action => 'create', :controller => 'prospects'),
:method => 'post' do |f| %>
<%= f.error_notification %>
<%= f.input :name, placeholder: 'Name', label: false %>
<%= f.input :email, placeholder: 'Email', label: false %>
<%= f.input :interests, placeholder: 'Tell us what you were searching for', label: false, value: params[:search] %>
<%= f.error :base %>
<%= f.button :submit, "Submit", :class=> "btn" %>
<% end %>
Using this partial:
<%= render partial: 'prospects/novideo_capture' %>
The partial is in a view controlled by Videos#index controller, and I keep getting this error: 'undefined method `model_name' for NilClass:Class'
This is my prospects controller:
class ProspectsController < ApplicationController
def index
#prospects = Prospect.all
end
def new
#prospect = Prospect.new
end
def create
#prospect = Prospect.new(params[:prospect])
if #prospect.save
render "thanks_for_interest"
else
render "novideo_capture"
end
end
I'm not sure what I'm going wrong, although I'm pretty sure it's a simple solution. I've seen a lot of similar questions around SO and tried all their answers, but none of them seem to work for this situation.
Thanks for any help...
EDIT: Adding
#prospect = Prospect.new
to the videos index controller stops the error occurring, but I don't feel it's the right way to do this. It also doesn't actually make the form use the prospects controller.
EDIT2: I now have the partial rendering correctly (I think), and my videos#index calls the partial like this:
<%= render partial: 'prospects/novideo_capture', :prospect => #prospect %>
Then simple_form in the partial looks like this:
<form class="form-inline">
<%= simple_form_for :prospect,
:url => url_for(:action => 'create', :controller => 'prospects'),
:method => 'post' do |f| %>
...
<% end %>
However it's not actually submitting the form with the prospects controller. Any ideas why?
Check your markup. You're wrapping a simple_form inside another form. Since the first form tag has no action associated with it (<form class="form-inline">), that form will submit against the current URL, which is the video#index.
You're going to want something like this:
<%= simple_form_for :prospect, :url => etc, :method => 'post', :class => "form-inline" do |f|
...
<% end %>
Losing the leading (redundant) form-inline form tag and you'll be fine.

Create a select from existing or create new in a form Rails 3

So I'm trying to set a name attribute of organizations and create a new organization or choose from a previously existing organization from the same form.
I've tried to follow Ryan Bates' railscast on the topic here: http://railscasts.com/episodes/57-create-model-through-text-field
I have also tried numerous solutions from stack. However, I can't quite seem to get it to run (that and I have a validation that does not recognize the virtual attribute I'm using)
so my organizations model:
class Organization < ActiveRecord::Base
has_many :materials
has_many :users
has_and_belongs_to_many :causes
has_and_belongs_to_many :schools, :join_table => 'organizations_schools'
####The following line has been edited ####
attr_accessible :name, :unlogged_books_num, :id, :new_organization_name
attr_accessor :new_organization_name
before_validation :create_org_from_name
validates_presence_of :name
def self.assign_school_to_organization(org, school)
orgschool = OrganizationsSchool.create(:organization_id=> org.id, :school_id=> school[0])
end
def create_org_from_name
create_organization(:name=>new_organization_name) unless new_organization_name.blank?
end
end
I have also tried the create_org_from_name as the following:
def create_org_from_name
self.name = new_organization_name
end
And this does not change the name to the organization name before validating or saving the instance.
I have also tried to change the before_save to before_validation, and that has not worked
My controller for organization (I also tried to change this in create)
def create
respond_to do |format|
#organization = Organization.new(params[:organization])
#organization.name = #organization.new_organization_name unless #organization.new_organization_name.blank?
if #organization.save
#school = params[:school]
Organization.assign_school_to_organization(#organization, #school)
format.html { redirect_to #organization, notice: 'Organization was successfully created.' }
format.json { render json: #organization, status: :created, location: #organization }
else
format.html { render action: "new" }
format.json { render json: #organization.errors, status: :unprocessable_entity }
end
end
end
And finally, I have what my form is doing currently:
<%= 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 %>
<% #schools = School.all %>
<% #organizations = Organization.all %>
<div class="field">
<%= f.label 'Organization Name' %><br />
<%= f.collection_select(:name, #organizations, :name, :name, :prompt=>"Existing Organization") %>
Or Create New
<%= f.text_field :new_organization_name %>
</div>
<div class="field">
<%= f.label :unlogged_books_num %><br />
<%= f.number_field :unlogged_books_num %>
</div>
<div class="field">
<%= f.label 'School' %><br />
<% school_id = nil %>
<%= collection_select(:school, school_id, #schools, :id, :name) %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
==================================EDIT============================================
So currently, when I try to make an organization with something only written in the virtual text field, My log tells me the following:
Processing by OrganizationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"igoefz8Rwm/RHrHLTXQnG48ygTGLydZrzP4gEJOPbF0=", "organization"=> {"name"=>"", "new_organization_name"=>"Virtual Organization", "unlogged_books_num"=>""}, "school"=>["1"], "commit"=>"Create Organization"}
Rendered organizations/_form.html.erb (7.1ms)
Rendered organizations/new.html.erb within layouts/application (8.0ms)
Completed 200 OK in 17ms (Views: 12.2ms | ActiveRecord: 1.0ms)
================================EDIT 2============================================
So this is what I get from the rails console if I try to create a new organization running this command: Organization.create(:new_organization_name=>"Virtual Organization", :unlogged_books_num=>"3")
irb(main):001:0> Organization.create(:new_organization_name=>"Virtual Organization", :unlogged_books_num=>"3")
(0.1ms) BEGIN
(0.1ms) ROLLBACK
=> #<Organization id: nil, name: nil, unlogged_books_num: 3, created_at: nil, updated_at: nil>
If the function of create_org_from_name is self.name = new_organization_name, then the result of the same command from the console is blank:
irb(main):002:1> Organization.create(:new_organization_name=>"Virtual Organization", :unlogged_books_num=>"3")
irb(main):003:1>
You need:
before_validation :create_org_from_name
and
def create_org_from_name
self.name = new_organization_name if not new_organization_name.blank?
end
You don't want to do a create in your before_validation method.

Ruby on Rails - Multibutton combined with checkboxes and advanced search

Currently I have the situation that one button is add to the index-form. This workes perfectly in combination with the other functionalties as search and checkboxes which are also part of the index-form.
Code of the index.html.erb:
<%= form_tag order_path, :method => 'get' do %>
<p>
<%= submit_tag "Historical Search", :account_short => nil %>
<%= text_field_tag :search, params[:search] %>
</p>
<% end %>
<%= form_tag sendnext_order_path, :method => :put do %>
<%= submit_tag "Send to Desk" %><br/>
-- other code from index-form
<% end %>
Combined with the controller:
def sendnext
Order.update_all(["status_id = ? ", "2"], :id => params[:order_ids])
redirect_to order_path, notice: 'Order succesfully send to desk.'
end
Now I want to add a second button next to the Send to Desk button with another action than the excisting working one. Until now I'm not capable to realise this.
Please advice. Any feedback is welcome.
Use button_to
<%= button_to('Send to Desk', 'sendnext', :method => "put") %>
<%= button_to('Cancel Order', 'cancelorder ', :method => "put") %>
Will take care of the form for you. submit_tag is submitting the first form I believe.
For example
<%= button_to "New", :action => "new" %>
will generate
# => "<form method="post" action="/controller/new" class="button_to">
# <div><input value="New" type="submit" /></div>
# </form>"
Thanks for your help. I have found a working solution which realised my current requirements:
The index.html.erb looks like the following:
<%= form_tag updateorder_order_path, :method => :put do %>
<%= submit_tag "To Desk" %><br/>
<%= submit_tag "Cancel Order" %>
-- other code like data fields
<%end %>
The controller.rb looks like the following:
def updateorder
if params[:commit] == "To Desk"
Order.update_all(["status_id = ? ", "2"], :id => params[:order_ids])
redirect_to order_path, notice: 'Order(s) successfully send to desk.'
elsif params[:commit] == "Cancel Order"
Order.update_all(["status_id = ? ", "3"], :id => params[:order_ids])
redirect_to order_path, notice: 'Order(s) successfully cancelled.'
else
Order.update_all(["status_id = ? ", "5"], :id => params[:order_ids])
redirect_to order_path, notice: 'Order(s) successfully updated.'
end
end
The routes.rb contains the next code:
resources :orders do
put 'updateorder', :on => :collection
end

Does a Rails plugin exist to build a show page (like a formbuilder)

I'm looking for a Rails plugin providing a builder for show.html.erb pages.
For example, with SimpleForm, an new.html.erb page might look like this :
<%= simple_form_for(#user, :url => user_registration_path, :html => ... }) do |f| %>
<%= f.input :email, :required => true %>
<%= f.input :password, :required => true %>
<%= f.input :password_confirmation, :required => true %>
...
<% end %>
But I was not able to find an equivalent for just displaying fields.
A generated show.html.erb page looks like :
<p>
<b>Email:</b>
<%= #user.email %>
</p>
...
But I'd like something like :
<%= simple_display_for(#user, :html => ... }) do |d| %>
<%= d.output :email %>
<%= d.output :name %>
...
<% end %>
Does this kind of builder exist?
Thanks
EDIT : If the builder use Twitter Bootstrap, that's even better :)
I don't know of any gems, but here is a simple example of how to build this feature yourself, which you can expand on:
lib/simple_output.rb
class SimpleOutput
def initialize(resource)
#resource = resource
end
def output(attribute)
#resource.send attribute
end
end
config/initializers/simple_output.rb
require_dependency 'lib/simple_output'
helpers/simple_output_helper.rb
module SimpleOutputHelper
def simple_output_for(resource, options={}, &block)
content_tag :div, yield(SimpleOutput.new(resource)), options[:html] || {}
end
end
users/show.html.erb
<%= simple_output_for(#user, html: { style: "background-color: #dedede" }) do |r| %>
<%= r.output :name %>
<%= r.output :email %>
<% end %>
Now, obviously this is just a very simple example, but hopefully it will get you started on the right track. Look at the simple_form source to see how they organize their code, and how they "typecast" fields. The simple_form codebase is very clean and easy-to-follow Ruby, and is a great example of what a gem should look like.

No Method Error for "comments", can't find and correct the nil value to make the comment post

I'm relatively new to rails and am trying to pull off my first polymorphic association with comments.
I am running rails 3.2.3
Edit - When I try to post a comment, my log is returning this error:
Started POST "/comments" for 127.0.0.1 at 2012-05-20 13:17:38 -0700
Processing by CommentsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"SOLcF71+WpfNLtpBFpz2qOZVaqcVCHL2AVZWwM2w0C4=", "comment"=>{"text"=>"Test this comment"}, "commit"=>"Create Comment"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 101 LIMIT 1
Completed 500 Internal Server Error in 126ms
NoMethodError (undefined method `Comment' for nil:NilClass):
app/controllers/comments_controller.rb:13:in `create'
I have tried out many different solutions offered on SO and elsewhere, including the answer from Jordan below, due, I'm sure, to my own inexperience, but have been unable to resolve the error.
The trace calls out line 13 in the Comments Controller and I commented after that line below to mark the error:
class CommentsController < ApplicationController
def index
#commentable = find_commentable
#comments = #commentable.comments
end
def new
#post = Post.find(params[:post_id])
end
def create
#commentable = find_commentable
#comment = #commentable.comments.build(params[:comment]) #<<<<LINE 13
if #comment.save
flash[:notice] = "Successfully created comment."
redirect_to :id => nil
else
render :action => 'new'
end
end
private
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
end
Posts Controller:
def show
#post = Post.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render :json => #post }
end
end
Comment template (in post show)
<ul id="comments">
<% if #comments %>
<h2>Comments</h2>
<% #comments.each do |comment| %>
<li><%= comment.text %></li>
<% end %>
<% else %>
<h2>Comment:</h2>
<% end %>
</ul>
<%= simple_form_for [#commentable,Comment.new], :html => { :class => 'form-horizontal', :multipart => true } do |f| %>
<fieldset>
<%= f.input :text %>
Upload Photo <%= f.file_field :photo %>
</fieldset>
<div class="form-actions">
<%= f.submit nil, :class => 'btn btn-primary' %>
</div>
<% end %>
Post show:
<p id="notice"><%= notice %></p>
<div class="row">
<div class="span2 offset1">
<%= image_tag #post.photo.url(:show) %>
</div>
<div class="span5">
<h1><%= #post.title %></h1>
<p><%= #post.index_text.html_safe %></p>
<p><%= #post.show_text.html_safe %></p>
<%= render "comments/comment" %>
<%= render "comments/form" %>
<% if can? :update, #course %>
<%= link_to 'Edit Post', edit_post_path(#post), :class => 'btn btn-mini' %>
<%= link_to 'Delete Post', #post,
confirm: 'Are you sure?',
method: :delete,
:class => 'btn btn-mini' %>
<%= link_to 'New Post', new_post_path, :class => 'btn btn-mini' %>
<% end %>
</div>
<nav class="span2 offset1">
<ul class="well">
<li>Category 1</li>
<li>Category 2</li>
</ul>
</nav>
</div>
<div class="row offset2">
<%= link_to 'Back to Posts', posts_path, :class => 'btn btn-mini' %>
</div>
Routes:
resources :posts, :has_many => :comments
resources :comments
It is probably something obvious that someone with more experience can resolve. Let me know if anything comes to mind. Brian
The problem is that #commentable is nil, which means that CommentsController#find_commentable is returning nil. I think your regular expression is sound, so that means one of two things is happening in find_commentable:
There aren't any keys in params that match your regex.
Your regex is matching but there aren't any records in the resulting table with the id in value.
Debug this as usual by inspecting params and the records in your database to make sure they look like you expect them to look.
The problem is your find_commentable method.
Here are the params passed to your CommentsController#create:
Started POST "/comments" for 127.0.0.1 at 2012-05-20 13:17:38 -0700
Processing by CommentsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"SOLcF71+WpfNLtpBFpz2qOZVaqcVCHL2AVZWwM2w0C4=", "comment"=>{"text"=>"Test this comment"}, "commit"=>"Create Comment"}
Here is your CommentsController#create:
def create
#commentable = find_commentable
#comment = #commentable.comments.build(params[:comment]) #<<<<LINE 13
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
As you can see, find_commentable expects a param like xx_id (for example, comments_id) which it uses to search for an appropriate class (in case of comments_id, it will be Comment), otherwise it returns nil. Refer classify and constantize here.
Your params do not contain any such param. So, you always get a nil object.
Your find_commentable needs some rework. I think in case of nested_fields, it should be an expression like
/(.+)_attributes$/
instead of
/(.+)_id$/.
And you need to have
:accepts_nested_attributes_for :commentable
in your Comment model class.
I tried both of the above answers, but the problem continued.
I ended up consulting with a friend who suggested the following solution, which I like because it's more elegant than my original attempt and easier to read (for later, when I or someone else need to return to the code):
def find_commentable
if params[:post_id]
Post.find(params[:post_id])
#elsif params[:other_id]
# Other.find(params[:other_id])
else
# error out?
end
end
The commented out section will refer to other associations once I get them up and running.