Getting ActionViewTemplate error in Heroku but not local rails environment - ruby-on-rails

I am deploying to Heroku and keep getting an error when loading the form to create a new room
ActionView::Template::Error (undefined method 'attractions' for Room)
I have added :attractions in permitted params in the RoomsController
params.require(:room).permit(:attractions)
and this is what the attractions text field looks like in the form
<%= form_for #room, html: {multipart: true} do |f| %>
<label for="textarea2" style="font-size: 17px; color: #0089ec;">Neighborhood Attractions</label>
<%= f.text_area :attractions, autofocus: true, :placeholder => "What tourist attractions are in your city", :class => "materialize-textarea" %>
This is the migration created to add the attractions field
class AddAttractionsToRoom < ActiveRecord::Migration
def change
add_column :rooms, :attractions, :text
end
end
and finally in the show page I have this
<div class="col m8 offset-m1 s12">
<p class="grey-text"><%= #room.attractions %></p>
</div>
Does anybody know why this is happening? Thanks
UPDATE:
So i checked the logs and found the problem is that i made migration errors and rake was aborting before the attractions field is created.
Here is the mess i made:
first i add a city_limit boolean field
class AddAmenitiesToRoom < ActiveRecord::Migration
def change
add_column :rooms, :city_limit, :boolean
end
end
then for some reason I forgot I had created the city_limit boolean field and instead thought I had a city string field. So I thought I should rename it to city_limit with this migration
class ChangeColumnName < ActiveRecord::Migration
def change
change_column :rooms, :city, :city_limit, 'boolean USING CAST(test_type AS boolean)'
end
end
And finally I decided, you know what, I think I need a city string field after all for geolocation so added another migration
class AddAcityToRoom < ActiveRecord::Migration
def change
add_column :rooms, :city, :string
end
end
Embarrassing, I know. Staying up late coding away is never good. But the problem can be easily fixed by removing this migration,
class ChangeColumnName < ActiveRecord::Migration
def change
change_column :rooms, :city, :city_limit, 'boolean USING CAST(test_type AS boolean)'
end
end
I just dont know if deleting the migration file is a good idea since I have already run rake db:migrate and there are about 10 other migrations after this one so rake db:rollback is not really an option

Perhaps is a problem of static assets....
Try to install gem 'rails_12factor'
gem 'rails_12factor', group: :production
bundle install

Related

rails globalization "undefined method for translates" error

after watching rails cast: https://www.youtube.com/watch?v=u6CMY3mUv90
i tried myself to globalize my rails project but i am getting "undefiend method for translates" error
gem 'globalize'
i did a bundle install in my bash terminal and also did bundle updates sucessfully
then i added "translates: title, :content" like below:
class Post < ActiveRecord::Base
belongs_to :admin
has_many :comments
rails_admin do
edit do
field :title
field :content, :ck_editor
field :link_title
field :link
field :admin
end
end
translates: title, :content
end
then i added
class TranslatePosts < ActiveRecord::Migration
def self.up
Post.create_translation_table!({
:title => :string,
:text => :text
}, {
:migrate_data => true
})
end
def self.down
Post.drop_translation_table! :migrate_data => true
end
end
AND i did rake db:migrate
but i am getting the erro still. any idea why it is not working?
Two things to be checked;
- It seems that you missed colon in the translated attributes :title.
- Restart rails server may be helpful.

facing issues in enum field in rails4

Hi I have generated a migration to add_column rails g migration AddColumnToEmployees
class AddColumnToEmployees < ActiveRecord::Migration
def change
add_column :employees, :role, "enum('SUPER-ADMIN', 'HR','ADMIN','INVENTORY','EMPLOYEE')", :default => 'EMPLOYEE'
end
end
run rake db:migrate
Now I want to access role in my view for this I have written this:
<%=f.select :role, :collection => Employee.roles %>
But its not accessing it. It gives error
undefined method 'roles' for #<Class:0xc2acd88>
Please guide how to solve this. Thanks in advance!
I was under the impression you represented the enum as an integer in the DB, so your migration should be:
class AddColumnToEmployees < ActiveRecord::Migration
def change
# Assuming Employee is the first value in your enum list
add_column :employees, :role, :integer, default: 0
end
end
and your select should be:
<%= f.select :role, :collection => Employee.roles.keys.to_a %>
See Saving enum from select in Rails 4.1
Your model:
class Employee
enum role: [:employee, :inventory, :admin, :hr, :superadmin]
end
Rails does automatically provide you with all potential values through a class method with the pluralized attribute name.
your migration is fine. after your migration to access it in view like that
<%=f.select :role, :collection => Employee.roles.keys.to_a %>
and define enum field in model employee.rb
enum role: {
super_admin: 1,
hr: 2,
admin: 3,
inventory: 4,
employee: 5
}
convert in enum role of model into hash. and assign the value. and run it.i will try my best hope it will help you!!
Try following code, I hope this will help you.
in AddColumnToEmployees migration file.
class AddColumnToEmployees < ActiveRecord::Migration
def change
add_column :employees, :role, :integer, default: 0
end
end
in Employee Model.
class Employee
enum role: [ :super_admin, :hr, :admin, :inventory, :employee ]
end
and finally in view file.
<%= f.select :role, options_for_select(Employee.roles.collect { |e| [e[0].humanize, e[0]] }) %>

Rails: Reference to new Model throwing error

I have a working users table.
I have generated a new table using:
rails generate model quiz_answers
..and run rake db:migrate
My CreateQuizAnswers migration file looks like this:
class CreateQuizAnswers < ActiveRecord::Migration
def change
create_table :quiz_answers do |t|
t.references :user, index: true
t.string :answer1
t.string :answer2
t.string :answer3
t.string :answer4
t.string :answer5
t.string :answer6
t.string :answer7
t.string :answer8
t.timestamps
end
end
end
I have a quiz_answer model:
class QuizAnswer < ActiveRecord::Base
belongs_to :user
end
and a QuizAnswersController:
class QuizAnswersController < ApplicationController
def new
#user = current_user
#quiz_answer = current_user.quiz_answer.build
end
private
def post_params
params.require(:quiz_answer).permit(:body, :user_id)
end
end
I have added :quiz_answers as a resource in routes.rb
Edited question:
WHY, then, when I try to build a form (using Devise) do I get the error "undefined method `body' for...(with a reference to QuizAnswer here)"? I have another model 'Post' which does not generate this error and does not have a 'body' attribute.
The page where I'm trying to build the form is home/whattypeofleader.html.erb and, in routes.rb I have:
get "whattypeofleader" => "home#whattypeofleader"
And in my HomeController I have:
class HomeController < ApplicationController
def index
end
def whattypeofleader
#user = current_user
#quiz_answer = current_user.quiz_answer.build
end
end
What the HELL am I doing wrong? Any help desperately appreciated, thanks.
Oh, and in case you need it, here's the form code, a partial that gets 'rendered' in whattypeofleader:
<%= form_for([current_user, #quiz_answer]) do |f| %>
<p>
<%= f.text_area :body, :autofocus => true , :class => "elearning-input"%>
</p>
<p>
<%= f.submit("Save entry") %>
</p>
<% end %>
<%= form_for([current_user, #quiz_answer]) do |f| %>
#...
<%= f.text_area :body, :autofocus => true , :class => "elearning-input"%>
You are creating a text_area here, and you tell rails to bind this text area input with a #quiz_answer.body attribute. Why?
form_for assigns last element of an array to be a form's object. It yield a form builder object (f), which keeps a reference to this object (f.object). All the fields created with this form builder are automatically populated with a value of f.object.send(:field_name) (it also set up a name of the fields, so the params can be easily matched when it is posted). This is rails magic making all the form fields populated with model's data.
Since your model does not have body attribute (no such column in your database and no method with that name defined), f.object.send(:body) throws a method undefined error.
Regarding the fix to that, you need to decide how this form is to look for. Your models contain 8 columns, answer<i> (which is worrying and suggests you might wanna use association here).

How do I fix NoMethodError when trying to create a pin in ruby?

Excuse me for maybe being naive, this is my first time using StackOverflow and I'm trying to learn ruby. I'm making an application through onemonthrails.com's tutorial that is similar to pinterest. I'm trying to add a pin and I keep getting the error:
NoMethodError in Pins#new
Showing /Users/jake/code/omrails/app/views/pins/_form.html.erb where line #5 raised:
undefined method `description' for #
Extracted source (around line #5):
I dont know what all will help you answer the question so I'll post all the files I received (that may be relevant to the question) when I ran the following command:
$ rails generate scaffold Pins
the migration file:
class CreatePins < ActiveRecord::Migration
def change
create_table :pins do |t|
t.string :description
t.timestamps
end
end
end
the model:
class Pin < ActiveRecord::Base
attr_accessible :description
end
_form.html.erb: (This is where it found the error)
<%= simple_form_for(#pin) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :description %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
new.html.erb: (this is "trace of template conclusion")
<h1>New pin</h1>
<%= render 'form' %>
<%= link_to 'Back', pins_path %>
I don't understand the error because I thought the method was defined in the model under attr_accessible :description
I'd appreciate your help if you can understand anything i just said. If not thanks for taking the time to look at it.
You need to run the migrations to create the pins table.
rake db:migrate
If it complains that the table exists, this means that you ran the migration before adding the description column. Rerunning the migration won't work without first reverting it:
rake db:migrate:redo
To clarify your point about attr_accessible :description - attr_accessible does not define the attribute for your model. Your database table does that (usually as per your migrations). What attr_accessible does is act as a whitelist for mass-assignable attributes.
I'm assuming you did not rake db:migrate after you created your scaffold. Try that first.
I don't understand the error because I thought the method was defined
in the model under attr_accessible :description
The attr_accessible :description declaration doesn't actually define the method. ActiveRecord does that under the hood for you based on the columns in your pins table. If you did not run the migration (and therefore create your table) ActiveRecord will not be able to auto generate attribute methods on your model, which could very well cause the error you're seeing.
attr_accessible declares your attributes accessible for being set via mass assignment. Typically, when you do this in your controller: #pin = Pin.new params[:pin] where params[:pin] is a hash of your model's attributes.
Could you check you database table "pins" having description column? If not, try to drop your previous table and try to create new one with description column.
or you can create a migration file to update your existing table, like:
rails g migration add_description_to_pins
then inside this file:
class AddDescriptionToPins < ActiveRecord::Migration
def self.up
add_column :pins, :description, :string
end
def self.down
remove_column :pins, :description
end
end

Mechanize mass assignment error for HABTM join table

The problem is that I get this error:
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: amenity_id
when I run this code:
task import_amenities: :environment do
agent = Mechanize.new
Kindergarten.find_all_by_public(false).each do |k|
p = agent.get(k.uri)
amenities = p.search("td td tr:nth-child(11) td:nth-child(2)").text.split(/(;|,) */)
amenities.each do |a|
am = Amenity.find_or_create_by_name!("#{a}")
k.update_attributes(amenity_id: am.id)
end
end
end
Kindergartens and Amenities are linked through a HABTM relation and are are defined as below:
kindergarten.rb
class Kindergarten < ActiveRecord::Base
attr_accessible :location, :name, :public, :uri, :address, :contact,
:phone, :url, :email, :description,
:password, :password_confirmation, :amenity_ids
has_and_belongs_to_many :amenities
end
amenity.rb
class Amenity < ActiveRecord::Base
attr_accessible :name, :kindergarten_ids
has_and_belongs_to_many :kindergartens
end
and here's the migration for the join table:
class CreateKindergartensAmenitiesJoinTable < ActiveRecord::Migration
def up
create_table :kindergartens_amenities, :id => false do |t|
t.integer :kindergarten_id
t.integer :amenity_id
end
end
end
The error is caused by this line in the rake task:
k.update_attributes(amenity_id: am.id)
Everything seems to work great in the console until I reach the mass assignment. And I think i am really messing something up here since I've never used before HABTM.
Any thoughts?
I couldn't sleep last night because of this bug but I finally found the solution.
there are a few issues in the code and the first one i noticed once i started digging and adding data in the db manually is that the join table is wrongfully named. Fix for that:
class RenameKindergartensAmenitiesTable < ActiveRecord::Migration
def up
rename_table :kindergartens_amenities, :amenities_kindergartens
end
end
apparently the habtm association is has to have stuff put alphabetically in title. source
Second problem is that I assumed that
k.amenity_id = am.id
would add an amenity_id / kindergarten_id for each amenity existing. In fact k.amenity_id does not mean anything (especially in the case of many ids). The solution that worked is this:
amenities.each do |a|
am = Amenity.find_or_create_by_name!("#{a}")
k.update_attributes(amenity_ids: k.amenity_ids.push(am.id))
end
I haven't modified the attr_accessible anywhere

Resources