Legacy Database CarrierWave Integration - mysql

I am having legacy database
Rails 3.2 & ruby 1.9.3p448
I wanted to develop active_admin back-end application
I wanted use CarrierWave File Uploads gem for uploading image
Following is my code in admin/item_master.rb i.e in view
form :html => { :enctype => "multipart/form-data" } do |f|
f.inputs "Item Details" do
f.input :IMTNAME
f.input :IMTBRIEFDESC
f.input :IMTDETAILDESC
f.input :IMTIMAGE, :as => :file
end
f.actions
end
Following is my code in model
class ItemMaster < ActiveRecord::Base
set_table_name "MDIMT"
attr_accessible :IMTNAME, :IMTBRIEFDESC, :IMTDETAILDESC, :IMTIMAGE
mount_uploader :IMTIMAGE, ImtimageUploader
end
It givesme Following Error
NameError in Admin::ItemMastersController#update
uninitialized constant IMTIMAGE

Related

Getting error (undefined method) for form_with

I have _form.html.erb. and on the first line of code, it is throwing this error:
undefined method `assessments_path' for #ActionView::Base:0x00000000229750
Did you mean? asset_path
couple of points:
in routes 'poweruser' is a namespace
in models assessment.rb is
not folder poweruser (as I plan to use it for other pages that anyone can access not just powerusers).
Any ideas what I am missing?
Here is the code:
<%= form_with(model: [#assessment], local: true) do |form| %>
<%= render "shared/error_messages", resource: form.object %>
<div class="form-group">
<%= form.label :name %>
<%= form.text_field :name, class: "form-control" %>
</div>
<% end %>
Here is the controller
module Powerusers
class AssessmentsController < ApplicationController
before_action :authenticate_user!
# before_action :set_assessment
# before_action :set_assessment, only: [:set_assessment, :show, :edit, :update, :destroy]
# Overwrite any of the RESTful controller actions to implement custom behavior
# For example, you may want to send an email after a foo is updated.
#
# def update
# super
# send_foo_updated_email(requested_resource)
# end
def index
#pagy, #assessments = pagy(Assessment.sort_by_params(params[:sort], sort_direction))
# We explicitly load the records to avoid triggering multiple DB calls in the views when checking if records exist and iterating over them.
# Calling #assessments.any? in the view will use the loaded records to check existence instead of making an extra DB call.
#assessments.load
end
# GET /assessments/new
def new
#assessment = Assessment.new
#assessment.assessment_sections.new
end
here is the assessment.rb (not it is not in a sub-folder poweruser)
class Assessment < ApplicationRecord
belongs_to :company
has_many :assessment_sections, inverse_of: :assessment
has_many :questions, through: :assessment_sections
accepts_nested_attributes_for :assessment_sections, reject_if: :all_blank,
allow_destroy: true
accepts_nested_attributes_for :questions, reject_if: :all_blank,
allow_destroy: true
end
Here is the routes
# PowerUser
authenticated :user, lambda { |u| u.admin? } do
namespace :powerusers do
resources :assessments do
resources :assessment_sections do
resources :questions
end
end
end
end
As you have namespace in routes, you need to specify that with form_with
<%= form_with(model: [:powerusers, #assessment], local: true) do |form| %>

Nested controllers Form_with Devise Error

So, I have a RailsApp and I decided to do a nested controller to my users called backoffice.
My routes to index are working fine, but when I try to edit or create a user, I get the following error:
NoMethodError in Backoffice::Users#new
undefined method `users_path' for #<#
<Class:0x007efc6d4fd1c8>:0x007efc6cd38708>
Did you mean? user_session_path
Here are my routes:
Rails.application.routes.draw do
resources :advertises
resources :categories
devise_for :users
namespace :backoffice do
resources :users, except: [:show]
end
end
I'm using Rails 5.1.4, so the 'form_tag' and 'form_for' are replaced for the 'form_with'
Here are my _form.html.erb where are my problem:
<%= form_with(model: user, root: true) do |form| %>
The structure of the controller is
class Backoffice::UsersController < BackofficeController
before_action :set_user, only: [:show, :edit, :update, :destroy]
before_action :pundit_user
....
Could the problem be with devise? Or it's just a nested controller error?
You should probably move the devise_for call into the :backoffice namespace as that is where the users resource is located.
If you run rails routes in the command line you will see the problem. Devise is trying to call users_path but that doesn't exist, what exists is backoffice_users_path

mysql Databases how can I fix this?

Hi Im trying to set up a database to store emails using ruby, sinatra, ActiveRecord, and mysql. Any suggestions on what im doing wrong? Im trying to output it to a seperate page that only i can see and then post it using a url on hostgator.
require 'sinatra'
require 'activerecord'
# require 'sinatra-activerecord'
get '/' do
erb :index
end
def save_email (email)
file.print(email)
end
get '/email' do
params[:email]
# # redirect '/'
end
post '/email' do
params[:email]
#email = params[:email]
erb :email, :locals => {:email => params[:email]}
end
# Change the following to reflect your database settings
ActiveRecord::Base.establish_connection(
adapter: 'mysql', # or 'postgresql'
host: 'localhost',
database: 'Stored_Emails',
)
class Stored_Emails < Sinatra::Application
end
class Stored_Emails < ActiveRecord::Base
end
ActiveRecord::Migration.create_table :email do |t|
t.string :emails
end
create_table :emails, force: true do |t|
t.string :email
t.belongs_to :email, index: true
end
get '/email' do
params[:email].all
end
Typically you break out your code into multiple files (we use folders named config, helpers, libraries, views, routes, models, migrations) and require them at the top of your app. However, if you want to put it in the same file and just use that and a Gemfile and Gemfile.lock that'll work too. Here's how it might look:
# Require your gems
require 'sinatra'
require 'activerecord'
# Libraries
# Models
class Stored_Emails < ActiveRecord::Base
end
# Configuration
# Change the following to reflect your database settings
ActiveRecord::Base.establish_connection(
adapter: 'mysql', # or 'postgresql'
host: 'localhost',
database: 'Stored_Emails'
)
ActiveRecord::Migration.create_table :email do |t|
t.string :emails
end
# Migrations
create_table :emails, force: true do |t|
t.string :email
end
# Helpers
def save_email (email)
file.print(email)
end
# Routes
get '/' do
# Load whatever you want to show in your index page into class variables
erb :index
end
get '/email' do
Stored_Emails.all.to_json
end
post '/email' do
#email = Stored_Emails.find_by(params[:email])
erb :email
end
Now you're going to have to do a good bit of work to get this running. Here's what I suggest you read:
1) Sinatra documentation - http://www.sinatrarb.com/intro.html
routes
running your sinatra app
views with ERB
2) Bundler documentation for gems - http://bundler.io/
3) ActiveRecord documentation - http://guides.rubyonrails.org/active_record_basics.html
Connecting to a database Creating your database with a migration -
this is a one time deal Querying the database
Good Luck!

why my mysql DB can read without update or insert data in Rails 4?

Guy I got something strange in my project
Now I got old ruby on rails project to develop some notes in it after I activate the commands
bundle
bundle exec rake db:create
bundle exec rake db:migrate
rails s
First the application asked me to install mysql2 0.3.14 and after installed it I got the error
log writing faild. invalid byte sequence in US-ASCII
and I solved it by added the #encoding: utf-8 in every first line in the project models
and finally now I can open my project well but
I found when I read data from my DB it work well when tried to insert or update any data from my MYSQL DB nothing happen with me !!!!! I thought that my DB user only take permissions to read only from the DB but after checked the user permissions I found it takes all the permissions
So can any one explain to me why I go this issue ????
This is a simple code to insert into my MYSQL DB
the View code
<%= form_for(#category) do |f| %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :icon %><br>
<%= f.file_field :icon %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
controller code
def create
#Just test to insert fixed data to my DB but also not insert any thing
#category =Category.new(:title => 'eeeee', :icon_file_name => 'xxx', :slug => 'sug')
##category =Category.new(:title => params[:title], :icon_file_name => params[:icon], :slug => params[:slug])
##category = Category.new(category_params)
respond_to do |format|
if #category.save
format.html { redirect_to #category, notice: 'Category was successfully created.' }
format.json { render action: 'show', status: :created, location: #category }
else
format.html { render action: 'new' }
format.json { render json: #category.errors, status: :unprocessable_entity }
end
end
end
Note: I'm using Windows 7
Seems like you didn't sanitize your params. In Rails 4 strong parameters have been introduced in order to increase security of untrusted sources posting data to your database.
So in your controller you have to add a private method (if you generated it with scaffolding it should be already present) to say which parameters to accept.
in your case should be something like
def category_params
params.require(:category).permit(:title, :icon_file_name, :slug, :whatever_other_param_you_need)
end
Read more here http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html

mysql keeps pulling select email NULL for session in RoR

I tried using Devise but since that didn't work out for me, I decided to build the authentication and sessions from scratch. I realize the problem wasn't devise, but it's mysql. For some reason, when I register a user, the information and attributes are stored in the database. When I login using the email and password, it keeps telling me that it's an invalid email/password. The log looks like this:
Processing by SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"NFudGruZS79uwDrKzbHDQrBjlcwQ7AkC958vI4aHDAs=", "session"=>{"email"=>"first#abc.com", "password"=>"[FILTERED]"}, "commit"=>"Sign in"}
User Load (0.4ms) SELECT `users`.* FROM `users` WHERE `users`.`email` IS NULL LIMIT 1
After some investigation, I know it's not because I didn't install mysql or other gems properly because a brand new app works just fine.
Does anyone know why it's not pulling the email I entered and pulling email is NULL instead?
Should I just create a new database and switch my database.yml file to the new database instead?
Thanks in advance.
EDIT - SOME MORE CODE
user model:
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :secondary_email, :password, :password_confirmation, :gender
has_many :user_owner_relationships
has_many :owners, :through => :user_owner_relationships
has_many :cash_endowments
has_many :checks, :through => :cash_endowments
has_many :owners, :through => :cash_endowments
email_regex = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, :presence => true,
:uniqueness => { :case_sensitive => false },
:format => { :with => email_regex }
validates :name, :presence => true,
:length => { :maximum => 40 }
validates :password, :presence => true,
:confirmation => true,
:length => { :within => 6..20 }
sessions_controller (user controller is standard)
def new
#title = "Sign in"
end
def create
user = User.authenticate(params[:email], params[:password])
if user
session[:user_id] = user.id
redirect_to root_path, :notice => "Welcome '#{user.first_name}"
else
flash.now.alert = "Invalid email or password."
render "new"
end
end
Rookie mistake -
It's actually because my new.html.erb for the sessions controller was not pulling the :session symbol from this code:
<%= form_for (:session, :url => sessions_path) do |f| %>
So I just ended up using form_tag instead.