NoMethodError in Controller, undefined error is not found anywhere in my code - ruby-on-rails-5.2

I have a course model and controller with some attributes including an image which i previously uploaded using carrierwave and it was working good then i wanted to implement ActiveStorage to store the image on s3 but failed so i reverted back to using carrierwave but now i get a "undefined method `image_size' for # Did you mean? image_was" i don't know from where and why this is being called. Please help.
i am strictly using the gems below:
gem 'rails', '5.2.0'
gem 'bootstrap-sass', '3.3.7'
gem 'puma', '3.9.1'
gem 'sass-rails', '5.0.6'
gem 'uglifier', '3.2.0'
gem 'coffee-rails', '4.2.2'
gem 'jquery-rails', '4.3.1'
gem 'turbolinks', '5.0.1'
gem 'jbuilder', '2.7.0'
gem 'bcrypt', '3.1.12'
gem 'carrierwave', '1.2.2'
gem 'mini_magick', '4.7.0'
gem 'aws-sdk-s3', require: false
class Course < ApplicationRecord
mount_uploader :image, CourseUploader
#has_one_attached :image
belongs_to :coordinator
validates :name, presence: true, length: {minimum: 4}
validates :prerequisite, presence: true, length: {minimum: 4}
validates :description, presence: true, length: {minimum: 4}
validate :image_size
validates :coordinator_id, presence: true
has_many :votes, dependent: :destroy
has_and_belongs_to_many :locations
has_and_belongs_to_many :categories
end
class CourseUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
# include CarrierWave::MiniMagick
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
def extension_whitelist
%w(jpg jpeg gif png)
end
end
class CoursesController < ApplicationController
def create
#course = current_coordinator.courses.build(course_params)
if #course.save
flash[:success] = "Course created!"
redirect_to current_coordinator
else
render 'new'
end
end
private
def course_params
params.require(:course).permit(:name, :prerequisite, :description, :image, category_ids: [], location_ids: [])
end
def set_course
#course = Course.find(params[:id])
end
end
<%= form_for #course do |f| %>
<%= render 'shared/error_courses', object: #course %>
<div class="field">
<%= f.label :name %>
<%= f.text_field :name,class: 'form-control' %><br>
<%= f.label :prerequisite %>
<%= f.text_field :prerequisite,class: 'form-control' %><br>
<%= f.label :description %>
<%= f.text_area :description, size: '20x5',class: 'form-control' %><br>
<%= f.label :category %>:
<%= f.collection_check_boxes :category_ids, Category.all, :id, :category %><br>
<br>
<%= f.label :location %>:
<%= f.collection_check_boxes :location_ids, Location.all, :id, :location %><br>
<!-- <%= f.label :image %> --><br>
<%= f.file_field :image %>
<div class="btn-sub">
<%= f.submit yield(:button_text), class: "btn btn-primary" %>
</div>
</div>
<% end %>
HERE IS THE LOG:
app/controllers/courses_controller.rb:27:in `create'
Started POST "/courses" for 127.0.0.1 at 2019-05-24 00:23:52 +1000
Processing by CoursesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"PwMJV5VdgTDulH2scefofWuA3AdtVamdTqbn6nXY5HxOJOgVlv7OjsakmXt2qqipDHOzh1FRybRB0EF10n3hlQ==", "course"=>{"name"=>"hshs", "prerequisite"=>"shsh", "description"=>"shahs", "category_ids"=>[""], "location_ids"=>[""]}, "commit"=>"Create a course"}
Coordinator Load (0.2ms) SELECT "coordinators".* FROM "coordinators" WHERE "coordinators"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
Category Load (0.1ms) SELECT "categories".* FROM "categories" WHERE 1=0
Location Load (0.1ms) SELECT "locations".* FROM "locations" WHERE 1=0
(0.1ms) begin transaction
(0.1ms) rollback transaction
Completed 500 Internal Server Error in 143ms (ActiveRecord: 3.4ms)
NoMethodError (undefined method `image_size' for #<Course:0x00007f802b4fba70>
Did you mean? image_was):
app/controllers/courses_controller.rb:27:in `create'

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

Not saving on the database from nested form

I want to create a dummy account for a new User object. Whenever a user signs up in my app it should automatically create an account for him.
But what's happening is, I'm saving in the database the new User, but not the new Account. I'm also not aware what's the best way to respect the MVC pattern design when it comes to this situation. I'm afraid of replicating code or to have one controller doing the work of two.
The sign up form, has nested resources (and it's build on top of devise)
<h2>Sign up</h2>
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<div><%= f.label :name %><br />
<%= f.text_field :name %></div>
<div><%= f.label :email %><br />
<%= f.email_field :email, :autofocus => true %></div>
<div><%= f.label :password %><br />
<%= f.password_field :password %></div>
<div><%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %></div>
<p>Account name</p>
<%= f.fields_for :account do |builder| %>
<fieldset>
<%= builder.label :title %>
<%= builder.text_field :title %>
</fieldset>
<% end %>
<div><%= f.submit "Sign up" %></div>
<% end %>
<%= render "devise/shared/links" %>
My User Model:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :accounts
accepts_nested_attributes_for :accounts
end
and my Account Model:
class Account < ActiveRecord::Base
belongs_to :user
end
My User Controller:
class UsersController < ApplicationController
def new
#user = User.new
end
def create
#user = User.new(user_params)
if #user.save
sign_in #user
##flash[:success] = "Welcome to the HighTide!"
redirect_to #user
else
render 'new'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation, accounts_attributes: [:id, :title])
end
end
and finally the Account Controller:
class AccountsController < ApplicationController
def new
#account = #user.accounts.new
end
def create
#account = current_user.accounts.new(account_params)
if #account.save
redirect_to '/'
end
end
private
def account_params
params.require(:account).permit(:title, :user_id, products_attributes: [:id, :title, :units], bookings_attributes: [:id, :name, :check_in, :check_out])
end
end
EDIT:
routes.rb file
Hightide::Application.routes.draw do
devise_for :users, path_names: {sign_in: "login", sign_out: "logout"}
resources :users do
resources :accounts
end
resources :sessions
match '/users/:user/edit', to: 'users#edit', via: [:post, :get]
devise_scope :user do
root to: 'static_pages#home'
match '/sessions/user', to: 'devise/sessions#create', via: :post
end
Your form_for can only send its data to a single controller method, and in this case it is sending the params from your form to the Devise registrations controller. Those params include the values for the new account, but they never reach your users#create or accounts#create methods.
You'll probably have to create a custom Devise controller. Take a look at this SO question and answer, which lays it out nicely. Nested registration data in Rails 3.1 with Devise.

Can't mass-assign protected attributes issue using devise signup form

I am using rails 3.1 and ruby 1.9.3 for my application.
And the issue is, I am getting "Can't mass-assign protected attributes" while saving the details.
I have User model as:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_one :profile
accepts_nested_attributes_for :profile
attr_accessible :email, :password, :password_confirmation, :remember_me, :profile_attributes, :first_name, :last_name
end
And Profile model as:
class Profile < ActiveRecord::Base
belongs_to :user
end
I am having few fields in "User" model and personal data like first_name, last_name and etc in "Profile" model. And I am trying to get all the required data by customizing the devise signup form as follows:
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<div><%= f.label :email %><br />
<%= f.email_field :email %></div>
<div><%= f.label :password %><br />
<%= f.password_field :password %></div>
<div><%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %></div>
<%= f.fields_for :profile do |builder| %>
<div><%= builder.label :first_name, "First Name" %><br />
<%= builder.text_field :first_name %></div>
<div><%= builder.label :last_name, "Last Name" %><br />
<%= builder.text_field :last_name %></div>
<% end %>
<div><%= f.submit "Sign up" %></div>
Can anyone please tell me where I am going wrong.
If the first_name and last_name fields are of the profile model then you should mention it as attribute_accessible in the profile model itself.
your profile model should look like
class Profile < ActiveRecord::Base
belongs_to :user
attribute_accessible :first_name, :last_name
end

How to add additional file fields to ruby on rails project?

Yesterday I have made paperclip multiple upload gallery. Today I want to customize this all and I need to make a button with on click add one more file upload field. Example you can see in this video: http://www.emersonlackey.com/article/rails-paperclip-multiple-file-uploads 28:27.
I have searched in google, but couldn't find anything.
#post form:
<% form_for #post, :html => {:multipart => true} do |t| %>
<p>
<%= t.label :title, 'Virsraksts:' %></br>
<%= t.text_field :title %></br>
</p>
<p>
<%= t.label :content, 'Teksts:' %>
<%= t.text_area :content, :class => "mceEditor"%>
</p>
<p>Pievienot jaunas bildes:</p>
<%= f.link_to_add "Add a task", :assets %>
<%= f.fields_for :assets do |asset_fields| %>
<% if asset_fields.object.new_record? %>
<%= asset_fields.file_field :asset %>
<%= asset_fields.link_to_remove "Noņemt" %>
<% end %>
<% end %>
<p>
<%= f.fields_for :assets do |asset_fields| %>
<% unless asset_fields.object.new_record? %>
<p>
<%= link_to image_tag(asset_fields.object.asset.url(:thumb)), asset_fields.object.asset.url(:original) %>
<%= asset_fields.check_box :_destroy %>
</p>
<% end %>
<% end %>
</p>
<%= t.submit %>
#post model:
class Post < ActiveRecord::Base
attr_accessible :title, :content, :assets_attributes
has_many :assets
accepts_nested_attributes_for :assets, :allow_destroy => true
end
#asset model:
class Asset < ActiveRecord::Base
belongs_to :post
has_attached_file :asset, :styles => { :large => "640x480", :medium => "300x300>", :thumb => "100x100>" },
:url => "/assets/albums/:id/:style/:basename.:extension",
:path => ":rails_root/public/assets/albums/:id/:style/:basename.:extension"
accepts_nested_attributes_for :post, :allow_destroy => true
end
There's a great cast from R.Bates about nested form here. i've modified it so that it's now possible to add, remove photos, works with paperclip, Feel free to clone this rails3.2 app https://github.com/Saidbek/multiple-image-uploader
You are going to need the javascript to make the functions to work.
If you are a railscasts premium user you can access the link above, as Said recommended, but if you not, you should take a look at this link.

Rails 3 I18n label translation for nested_attributes in has_many relationship

Using: Rails 3.0.3, Ruby 1.9.2
Here's the relationship:
class Person < ActiveRecord::Base
has_many :contact_methods
accepts_nested_attributes_for :contact_methods
end
class ContactMethod < ActiveRecord::Base
attr_accessible :info
belongs_to :person
end
Now when I try to customize the contact_method labels in I18n, it doesn't recognize it.
en:
helpers:
label:
person[contact_methods_attributes]:
info: 'Custom label here'
I have also tried:
person[contact_method_attributes]
This works just fine for 1-1 relationships, e.g.
person[wife_attributes]:
name: 'My wife'
but not person[wives_attributes]
Thanks in advance
I did this with :
en:
helpers:
label:
person[contact_methods_attributes][0]:
info: 'First custom label here'
person[contact_methods_attributes][1]:
info: 'Second custom label here'
Which is nice but not ideal when you have unlimited options.. I would just specify a custom translation key in the form builder :)
en:
helpers:
label:
person[contact_methods_attributes][any]:
info: 'Custom label here'
<% fields_for :contact_methods do |builder| %>
<%= builder.label :info, t("helpers.person[contact_methods_attributes][any].info") %>
<%= builder.text_field :info %>
<% end %>
EDIT :
Don't know if it's a new feature but seems to work like a charm doing this :
en:
helpers:
label:
person:
contact_methods:
info: 'Custom label here'
In my Rails 3.2.13 app the attribute labels are picked up automatically from the model whose attributes are embedded. Please note that I am nesting attributes of the belongs_to model, but it might also work the other way around.
My example from working code:
The models:
class User < ActiveRecord::Base
belongs_to :account
accepts_nested_attributes_for :account
# ...
end
class Account < ActiveRecord::Base
has_many :users
end
The view:
<h2><%= t(:sign_up) %></h2>
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<div><%= f.label :email %><br />
<%= f.email_field :email %></div>
<%= f.fields_for :account do |account_form| %>
<div><%= account_form.label :subdomain %><br />
<%= account_form.text_field :subdomain %>.<%= request.host %> <span class="hint"></span></div>
<% end %>
translations_de.yml:
activerecord:
models:
account: Konto
user: Benutzer
attributes:
account:
name: Firmenname
subdomain: Subdomain
users: Benutzer
user:
# ... no sign of subdomain here ...
And the view is rendered with the subdomain label translated based on
activerecord.attributes.account.subdomain
Nice. :)
I'm not sure but it might require you to use the activerecord path instead of the helpers one.

Resources