Ive been going through this for hours and i cant seem to find the problem. Im doing a simple contacts form in rails , this is a tutorial im following so bear with me. I get the following error message :
undefined method `name' for #
I have this in my DB/migrate file:
class CreateContacts < ActiveRecord::Migration
def change
create_table :contacts do |t|
t.string :name
t.string :email
t.text :comments
t.timestamps
end
end
end
this on my contacts_controller.rb file:
class ContactsController < ApplicationController
def new
#contact = Contact.new
end
def create
end
end
and this is on my pages_controller.rb:
class PagesController < ApplicationController
def homepage
end
def about
end
end
This is my html :
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="well">
<%= form_for #contact do |f| %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :email %>
<%= f.email_field :email, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :comments %>
<%= f.text_area :comments, class: 'form-control' %>
</div>
<%= f.submit 'Submit', class: 'btn btn-default' %>
<% end %>
</div>
</div>
</div>
Did you run your migration?
If not, do so:
bundle exec rake db:migrate
This will create the contacts table in your database (which has the name column along with other columns email and comments that you're using while building your form). Also, re-start your rails server and then you should be able to use your form code without any problem.
You have probably not migrated your table.
In your console run:
rake db:migrate
Then restart your server and try again.
The other answers summed it up well - you need to migrate your contacts table:
$ rake db:migrate
You'll want to read up on Rails migrations here.
As an aside,
Pages
I don't know which tutorial everyone seems to be following, it's telling you to use specific actions for static pages, which IMO is pretty bad practice (especially in the long run).
A much more versatile (and "Railsy*) solution is to put the content for the data in the database, which you can then call with a model - allowing you to have a single show view for all your pages:
#config/routes.rb
resources :pages, only: [:show]
#app/controllers/pages_controller.rb
class PagesController < ApplicationController
def show
#page = Page.find params[:id]
end
end
#app/views/pages/show.html.erb
<%= #page.title %>
<%= #page.body %>
You'd have to create another migration for the pages datatable, as follows:
$ rails g migration CreatePages
class CreatePages < ActiveRecord::Migration
def change
create_table :pages do |t|
t.string :title
t.text :body
t.timestamps
end
end
end
$ rake db:migrate
HTML
Your current HTML can be a lot more efficient:
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="well">
<%= form_for #contact do |f| %>
<% attributes = {name: "text_field", email: "email_field", comments: "text_area"} %>
<% attributes.each do |attr,val| %>
<div class="form-group">
<%= f.label attr.to_sym %>
<%= f.send(val, attr.to_sym, class: 'form-control') %>
</div>
<% end %>
<%= f.submit 'Submit', class: 'btn btn-default' %>
<% end %>
</div>
</div>
</div>
Related
I'm creating a database website using rails. I implemented where a user can upload an image. There are two places where you can upload an image, one for a vendor and other for the inventory. One of the model is called "photos" and the other "fotos". I'm new to rails and wasn't sure how to use the same model, "photos" to upload to the other part of the database, so I created the model "foto" and followed the tutorial. But now when you upload a photo, the button says "Create Foto". I want it to say "Create Photo". I'm not sure how to do this.
Some of my code files
_form.html.erb/fotos/view
<%= form_for([#vendor, #vendor.fotos.build]) do |f| %>
<div class="form-group1">
<%= f.label :image %>
<%= f.file_field :image, class: 'form-control1'%>
</div>
<p>
<%= f.submit %>
</p>
<% end %>
_foto.html.erb/fotos/view
<div class="media1">
<div class="media-left1">
<%= link_to image_tag(foto.image.url, class: 'media-object1'), foto.image.url, target: '_blank' %>
</div>
<div class="media-body1">
<h4 class="media-heading1"><%= foto.title %></h4>
</div>
</div>
<p>
<%= link_to 'Delete Photo', [foto.vendor, foto],
method: :delete,
data: { confirm: 'Are you sure?' } %>
</p>
show.html.erb/vendors/view
<body>
<div class = "head">
<h1>Vendor Information</h1>
<div class = "image1" >
<img src= "http://dx.deucex.com/i/logo.png" >
</div>
</div>
</body>
<%= render #vendor.fotos %>
<h3>Add a photo:</h3>
<%= render 'fotos/form' %>
<p>
<strong>Company:</strong>
<%= #vendor.company %>
</p>
<p>
<strong>Contact Name:</strong>
<%= #vendor.contact_name %>
</p>
<p>
<strong>Phone:</strong>
<%= #vendor.phone %>
</p>
<p>
<strong>Email:</strong>
<%= #vendor.email %>
</p>
<p>
<strong>MOQ:</strong>
<%= #vendor.moq %>
</p>
<p>
<strong>Cost/Item:</strong>
<%= #vendor.cost_per_item %>
</p>
<p>
<strong>Payment Method:</strong>
<%= #vendor.payment_method %>
</p>
<p>
<strong>Terms:</strong>
<%= #vendor.terms %>
</p>
<p>
<strong>Turnover Period:</strong>
<%= #vendor.turnover %>
</p>
<p>
<strong>Returns:</strong>
<%= #vendor.returns %>
</p>
<p>
<strong>Notes:</strong>
<%= #vendor.notes %>
</p>
<%= link_to 'Back', vendors_path %>
fotos_controller.rb
class FotosController < ApplicationController
def index
#fotos = Foto.order('created_at')
end
def new
#foto = Foto.new
end
def create
#vendor = Vendor.find(params[:vendor_id])
#foto = #vendor.fotos.create(photo_params)
redirect_to vendor_path(#vendor)
end
def destroy
#vendor = Vendor.find(params[:vendor_id])
#foto = #vendor.fotos.find(params[:id])
#foto.destroy
redirect_to vendor_path(#vendor)
end
private
def photo_params
params.require(:foto).permit(:title, :image)
end
end
foto.rb/model
class Foto < ApplicationRecord
has_attached_file :image
belongs_to :vendor
validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
end
migration file
class CreateFotos < ActiveRecord::Migration[5.1]
def change
create_table :fotos do |t|
t.string :title
t.references :vendor, foreign_key: true
t.timestamps
end
end
end
another migration file
class AddAttachmentImageToFotos < ActiveRecord::Migration[5.1]
def self.up
change_table :fotos do |t|
t.attachment :image
end
end
def self.down
remove_attachment :fotos, :image
end
end
<%= f.submit 'Create Photo' %>
This should rename the button. For more options use the following link
https://apidock.com/rails/ActionView/Helpers/FormBuilder/submit
There are two ways.
1. Pass a value to submit_tag
<%= f.submit 'Create Photo' %>
2. Use the I18N module
# config/locales/en.yml
en:
helpers:
submit:
foto:
create: "Create Photo"
This approach is better if you at some point intend to translate the application. It also makes it easy to use the same form for create and update and have the correct text for each.
I keep get this error when I want to render my form
The error is pointing the <%= form_for(#hreport) do |f| %>, I'm not sure where when wrong or i missed something, anyone help is appreciate!
<div class="col-md-6 col-md-offset-3">
<%= form_for(#hreports) do |f| %>
<%= f.label :"Student ID" %>
<%= f.text_field :studentid, class: 'form-control' %>
This is my health_report_controller.rb
class HealthReportController < ApplicationController
def index
#hreports = Healthreport.where(:user_id => current_user.id)
end
def new
#hreports = Healthreport.new
end
def create
#hreports = current_user.healthreports.build(hreport_params)
if #hreports.save
flash[:success] = "Report Submitted!"
else
end
end
def show
#hreports = Healthreport.find(params[:id])
end
private
def set_hreport
#hreport = Healthreport.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def hreport_params
params.require(:Healthreport).permit(:date, :studentid, :department, :issue)
end
end
This is my view
<% provide(:title, 'New Report') %>
<h1>Health and Safety Report</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_for(#hreports) do |f| %>
<%= f.label :"Student ID" %>
<%= f.text_field :studentid, class: 'form-control' %>
<%= f.label :"Department of applicant" %>
<%= f.text_field :department, class: 'form-control' %>
<%= f.label :"Description of Issues" %>
<%= f.text_area :issue, placeholder: "Write your report here...", class: 'form-control' %>
<%= f.submit "Submit", class: "btn btn-primary" %>
<% end %>
This is my healthreport.rb inside model folder
class Healthreport < ApplicationRecord
belongs_to :user
end
This is my healthreport.rb inside db folder
class CreateHealthreports < ActiveRecord::Migration[5.0]
def change
create_table :healthreports do |t|
t.datetime :date
t.string :studentid
t.string :department
t.string :issue
t.timestamps
end
end
end
It's migration db file
class AddUserToHealthreport < ActiveRecord::Migration[5.0]
def change
add_reference :healthreports, :user, foreign_key: true
end
end
In your controller, you do this:
def new
#hreports = Healthreport.new
end
But in the view, you are expecting this
<%= form_for(#hreport) do |f| %>
You are passing #hreports but trying to use #hreport. Change the controller to be
def new
#hreport = Healthreport.new
end
(the index action should use the plural, the other actions should use the singular)
Two Rails convention/style things you should be aware of:
A singular variable name (such as #hreport) refers to a single object; a plural of that name (#hreports) refers to an array or an ActiveRecord relationship.
Model and Controller should use the same naming style: if the controller is named health_report_controller.rb and defines a HealthReportController, then the model file should be named health_report.rb and should define a HealthReport class.
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 am new to ruby on rails and i am currently stuck trying to create a contact form.
I get the report saying : undefined method `name' for #, but in the i did create the method for name :
create_table :contacts do |t|
t.string :name
I'v tried to fix this error so i can preview the page, but i keep getting an error. I hope one of you can help me, thanks in advance!
NoMethodError in Contacts#new
Showing /home/nitrous/workspace/simplecodecast_saas/app/views/contacts/new.html.erb where line #7 raised:
undefined method `name' for #<Contact id: nil>
Extracted source (around line #7):
<%= form_for #contact do |f| %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %> <---- (This is line 7)
</div>
<div class="form-group">
Rails.root: /home/nitrous/workspace/simplecodecast_saas
Application Trace | Framework Trace | Full Trace
app/views/contacts/new.html.erb:7:in `block in _app_views_contacts_new_html_erb__2291340040590759835_34535240'
app/views/contacts/new.html.erb:4:in `_app_views_contacts_new_html_erb__2291340040590759835_34535240'
Request
Parameters:
None
Toggle session dump
Toggle env dump
Response
Headers:
None
My routes.rb code:
Rails.application.routes.draw do
resources :contacts
get '/about' => 'pages#about'
root 'pages#home'
and my contacts_controller.rb
class ContactsController < ApplicationController
def new
#contact = Contact.new
end
def create
end
end
I added this to my model: contact.rb
class Contact < ActiveRecord::Base
end
And the db file:
class CreateContacts < ActiveRecord::Migration
def change
create_table :contacts do |t|
t.string :name
t.string :email
t.text :comments
t.timestamps
end
end
end
and last my html page
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="well">
<%= form_for #contact do |f| %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :email %>
<%= f.email_field :email, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :comments %>
<%= f.text_area :comments, class: 'form-control' %>
</div>
<% f.submit 'Submit', class: 'btn btn-default' %>
<% end %>
</div>
</div>
</div>
I found a fix.
I ran the rake db:rollback cmd and then the rake db:migrate.
Now it is working.
Sorry for wasting your time :) Hopefully someone else can benifit from this answer!
I'm new in Ruby on Rails and I'm creating my own Ruby on Rails - Blog... For my tweets I'm creating a selfmade Scaffold...
Even i press the submit button.. for my new post.. i will get this error msg:
uninitialized constant PostsController
Here are my files:
new.html.erb
<h1>Add a new Tweet</h1>
<%= form_for(#post) do |f| %>
<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 %>
blog_controller.rb
class BlogController < ApplicationController
def new
#post = Post.new
end
def create
#post = Post.new(params[:post])
redirect_to #post
end
end
routes.rb
Me::Application.routes.draw do
resources :posts
resources :post
match '/' => 'blog#home'
match '/archiv' => 'blog#archiv'
match '/tweets' => 'blog#new'
root :to => 'blog#home'
end
I made a model with these syntax:
rails g model post title:string content:text
And at least rake db:migrate
solved by myself: made a new controller