I'm experiencing difficulties in implementing the Action Text gem to my Rails 5.2.1 application.
I followed the installation guide and the rich text editor wouldn't show up in my _form view.
I then realised that it requires Rails 6 with webpacker and active storage. Changing my gemfile's Rails version and running rails upgrade didn't work, so I added the webpacker and active storage gems and bundled it with my current 5.2.1 version. That didn't work either.
I'd really like to have a Rich Text Editor in my app. It is not a must that it is the Trix editor, but since it will be native as of v6 I thought it was the obvious choice.
References of my source code
GitHub: https://github.com/Curting/mydanceplan
Heroku: https://mydanceplan.herokuapp.com/
The perfect choice ,tested on my new application using rails 5.2.3 .
please not action text require ruby 2.5.3 up.
first : Add webpacker
You can either add Webpacker during setup of a new Rails 5.1+ application using new --webpack option:
Available Rails 5.1+
rails new myapp --webpack
Or add it to your Gemfile:
Gemfile
gem 'webpacker', '~> 4.x'
OR if you prefer to use master
gem 'webpacker', git: 'https://github.com/rails/webpacker.git'
yarn add https://github.com/rails/webpacker.git
Now add Actiontext to your gem file with image magic:
gem'actiontext',github:'kobaltz/actiontext',branch:'archive',require:'action_text'
gem 'image_processing'
Finally, run the following to install Webpacker:
bundle
bundle exec rails webpacker:install
rails action_text:install
rails db:migrate
brew install imagemagick vips
add this to your view/layout/application in the head section
#layouts/application.html.erb
<%= javascript_pack_tag 'application' %>
In your model , it may be an article or what ever in your model
class Article < ApplicationRecord
has_rich_text :content
end
in your controller
#controllers/articles_controller.rb
def article_params
params.require(:article).permit(:name, :content)
end
in your form
#_form.html.erb
<div class="field">
<%= form.label :content %>
<%= form.rich_text_area :content %>
</div>
finaly to display the content in your view;
<h1><%= #article.name %></h1>
<p><%= #article.content %></p>
Optional: To fix "unmet peer dependency" warnings,
yarn upgrade
you can watch the full video here:
https://www.driftingruby.com/episodes/using-action-text-in-a-rails-5-2-application
I have a partial answer for you! I wanted to use Trix, Rails 5.2.2, and Webpacker, but couldn't find a clear answer. The trix gem didn't work since I don't use the asset pipeline at all. (I also use Turbolinks and Stimulus, and so far this is working fine alongside those.)
I strung a solution together using:
trix node package
a custom form tag helper, derived from this Stack post
I can now use a form helper that looks like this (using the Slim templating language):
= f.trix :personal_notes, class: 'some-css-class'
To get there, I did the following:
yarn add trix
In my Javascript pack, import 'trix';
In my CSS pack, #import '~trix/dist/trix';
Then I created the form helper. Here's what that looked like:
In app/helpers/application_helper.rb, I added the new form helper, based on that Stack post I linked above. My file now looks like this:
module ApplicationHelper
# ...
class ActionView::Helpers::FormBuilder
# include ActionView::Helpers::TagHelper # I didn't need this.
include ActionView::Helpers::FormTagHelper
include ActionView::Helpers::FormOptionsHelper
# include ActionView::Helpers::CaptureHelper # I didn't need this.
# include ActionView::Helpers::AssetTagHelper # I didn't need this.
# since these tag helpers just return strings, it is easy to make a pretty
# powerful helper. It is probably possible to use existing Rails form
# helpers to aid this as well.
def trix(method, options = {})
value = (#object[method].empty?) ? '' : "value='#{#object[method]}'"
return "<input id='#{field_id(method)}' type='hidden' name='#{field_name(method)}' #{value}><trix-editor input='#{field_id(method)}' class='trix-content #{options[:class]}'></trix-editor>".html_safe
end
def field_name(label,index=nil)
return #object_name + "[#{label}]"
end
def field_id(label,index=nil)
return #object_name + "_#{label}"
end
end
end
Restart Rails. Seems to work for me.
Related
I have a blog application that I have created in Rails. I followed this tutorial.
So, I cannot find new.html.erb in my app/views/articles. I specifically created this file. The file, new.html.erb, located in app/views/articles holds the form that is required to create new article posts. I did a search through all of my Rails files and it is nowhere to be found. But the funny thing is, my Rails application is still fully functional. I can still create new article posts without any trouble. The reason I want the file is so I can add a Trix Rich Text Editor to the form. I noticed this problem after I installed one of the following gems:
gem 'rails_admin', github: 'sferik/rails_admin'
gem 'rails_admin_rollincode', '~> 1.0'
The path to create a new article post when running the server is localhost:3000/admin/articles/new.
You are using rails_admin. This gem builds forms on the fly for your models.
Find the relevant code in at /views/rails_admin/main/new.html.haml in the gem:
= rails_admin_form_for #object, url: new_path(model_name: #abstract_model.to_param), as: #abstract_model.param_key, html: { multipart: true, class: "form-horizontal denser", data: { title: #page_name } } do |form|
= form.generate action: :create
I don't have any problems using link_to locally however, as soon as I deploy to Heroku I get the following error:
users#show (ArgumentError) "arguments passed to url_for can't be handled. Please require routes or provide your own implementation"
app/views/users/show.html.erb:176:in `_app_views_users_show_html_erb__222687663100622833_69928454693640'
I am using ruby '2.2.0' and rails '4.2.0'
Any ideas on how to further debug this or replicate it locally?
Update 1. Here's the actual view code which displays pagination links. The resulting route should be /users/1?page=1 etc.
<div class="row text-center">
<%= will_paginate collection, renderer: BootstrapPagination::Rails %>
</div>
The issue was with url_helpers included in one of my models - everything worked after I removed the following include.
include Rails.application.routes.url_helpers
Using the correct url_for method in a Rails engine spec
I had the same issue with ActiveAdmin in production environment. In my case the issue was with ActionView::Helpers::FormTagHelper included at root level in one of my helpers.
I solved it moving the include statement inside a class defined in the same file.
Using Ruby 2.1.1 Rails 4.1.4
Hi,
I've been banging my head on a really strange issue I'm seeing with FormHelper. I'm simply trying to build a form using form_for and I'm getting the cannot call new for nil class error when the view tries to render. Through the backtrace, I found that the issue is actually in:
ActionView::Helpers::FormHelper#instantiate_builder:1145-1146
builder = options[:builder] || default_form_builder
builder.new(object_name, object, self, options)
default_form_builder is defined as follows in ActionView::Helpers::FormHelper
def default_form_builder
builder = ActionView::Base.default_form_builder
builder.respond_to?(:constantize) ? builder.constantize : builder
end
I have not added a Custom Form Builder and am simply trying to use the default. When I check what ActionView::Base.default_form_builder is, I get nil.
The 2 solutions to get it to work for me were:
Pass a Form Builder Object to the form_for options[:builder] hash
Add the following line in my environment config
config.action_view.default_form_builder = ActionView::Helpers::FormBuilder
I'm using 2) for now but both of these shouldn't be necessary.
I've looked everywhere but no luck with what is going on. Thanks for any help!
Did you have gem 'extlib' and gem 'devise' in Gemfile?
Move gem 'extlib' line under gem 'devise' line.
I don't know why but it will work...
I'm using the default I18n module for Rails to translate my strings in views.
<%= t("registration.heading") %>
Now, when I'm in the registration-view, all my strings start with registration. I always have to write
<%= t("registration.heading.notice") %>
// or
<%= t(:heading, :scope => :registration) %>
It would be nice to define a default scope for that file (maybe even in the controller), so a call to t automatically adds the defined scope
// controller
set_i18n_default_scope :registration
// view
<%= t(:heading) %>
// --> looks in "registration.heading"
Is this possible?
If you organize your translations adding a view name, as in:
en:
registration:
index:
heading: "Registration heading"
then you may use this:
<%= t(".heading") %>
Notice that the first character is a dot.
You may read about it in Rails Internationalization (I18n) API Guide
If you have texts which are shared amongst numerous views, and you don't want to copy the same translation in each section for each view, you may use YAML references. They are nicely described on wikipedia: http://en.wikipedia.org/wiki/YAML#Repeated_nodes
It is possible. Check section 4.1.4 of the Rails i18n API
4.1.4 “Lazy” Lookup
Rails 2.3 implements a convenient way
to look up the locale inside views.
When you have the following
dictionary:
es: books:
index:
title: "Título"
you can look up the books.index.title value inside
app/views/books/index.html.erb
template like this (note the dot):
<%= t '.title' %>
Regarding Lazy Lookups:
Here's the general solution for this kind of problem
Common Problem: Where is Rails trying to look-up L10N / I18N Strings? - e.g. when doing Lazy Lookups
It's not easy to guess, because it's different for Views, Controllers, Models, Labels, Helpers, or Validations... etc... but...
It's easy to find out directly, using this:
http://www.unixgods.org/Rails/where_is_Rails_trying_to_lookup_L10N_strings.html
this helps figuring out what Rails thinks the current scope is (e.g. when using ".heading")
3 Simple Steps:
create a file ./config/initializers/i18n.rb , as described in the article above
put t('.heading') in your view
start "rails server" and look in the console output where Rails thinks the default location is for '.heading' for this view... e.g. what's the I18N-key
(4. then add the I18N string into the location identified by the key)
Works like a charm :-)
If you want to print out keys that I18n gem's lazy mode is looking for, you can add that in a i18n.rb file in your initializers folder:
module I18n
module Backend
class Simple
module Implementation
alias_method :lookup_orig, :lookup
# Give ability to check I18n looked up keys in lazy mode by setting env var I18N_DEBUG to true
#
def lookup(locale, key, scope = [], options = {})
puts "I18N keys: #{I18n.normalize_keys(locale, key, scope, options[:separator])}" if ENV['I18N_DEBUG']
lookup_orig(locale, key, scope, options)
end
end
end
end
end
(Gist: https://gist.github.com/capripot/6e6cf778ad2db0443280)
And then start your server like for instance:
I18N_DEBUG=true bundle exec rails server
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Improve this question
I'd like to implement a captcha in a Rails project for a form submission, but I'm not sure what to go with. I'm inclining towards simplicity of implemention, and reliability when in use, over it being too sophisticated, as my application doesn't require too high a level of security.
Anyone have any recommendations?
The easiest way to add a CAPTCHA to your Rails application is using Ambethia reCAPTCHA:
1. Installation:
config.gem "ambethia-recaptcha", :lib => "recaptcha/rails",
:source => "http://gems.github.com"
You can install it as a plugin, too, if you like.
2. Get a reCAPTCHA account:
You have to create a reCAPTCHA key. You can do it on the reCAPTCHA site.
3. Usage:
Use recaptcha_tags to output the necessary HTML code and then verify the input with verify_recaptcha.
4. Further reading:
Ambethia reCAPTCHA
reCAPTCHA documentation
Installation
Add the following to your GEMFILE
gem "galetahub-simple_captcha", :require => "simple_captcha"
or
gem 'galetahub-simple_captcha', :require => 'simple_captcha',
:git => 'git://github.com/galetahub/simple-captcha.git'
Then run bundle install if you're using Bundler (or use the package manager for your Rails configuration)
Setup
After installation, follow these simple steps to setup the plugin. The setup will depend on the version of rails your application is using.
rails generate simple_captcha
rake db:migrate
Usage
Controller Based
Add the following line in the file “app/controllers/application.rb”
ApplicationController < ActionController::Base
include SimpleCaptcha::ControllerHelpers
end
In the view file within the form tags add this code
<%= show_simple_captcha %>
and in the controller’s action authenticate it as
if simple_captcha_valid?
do this
else
do that
end
Model Based
In the view file within the form tags add this code
<%= show_simple_captcha(:object=>"user") %>
and in the model class add this code
class User < ActiveRecord::Base
apply_simple_captcha
end
FormBuilder helper
<%= form_for #user do |form| -%>
...
<%= form.simple_captcha :label => "Enter numbers.." %>
...
<% end -%>
Validating with captcha
NOTE: #user.valid? will still work as it should, it will not validate the captcha code.
#user.valid_with_captcha?
Saving with captcha
NOTE: #user.save will still work as it should, it will not validate the captcha code.
#user.save_with_captcha
Formtastic integration
SimpleCaptcha detects if your use Formtastic and appends
“SimpleCaptcha::CustomFormBuilder”.
<%= form.input :captcha, :as => :simple_captcha %>
Options & Examples
View Options
*label* - provides the custom text b/w the image and the text field, the default is “type the code from the image”
*object* - the name of the object of the model class, to implement the model based captcha.
*code_type* - return numeric only if set to ‘numeric’
Global options
image_style - provides the specific image style for the captcha image.
There are eight different styles available with the plugin as…
simply_blue
simply_red
simply_green
charcoal_grey
embosed_silver
all_black
distorted_black
almost_invisible
Default style is ‘simply_blue’. You can also specify ‘random’ to select the random image style.
distortion - handles the complexity of the image. The :distortion can be set to ‘low’, ‘medium’ or ‘high’. Default is ‘low’.
*Create “rails_root/config/initializers/simple_captcha.rb”*
SimpleCaptcha.setup do |sc|
# default: 100x28
sc.image_size = '120x40'
# default: 5
sc.length = 6
# default: simply_blue
# possible values:
# 'embosed_silver',
# 'simply_red',
# 'simply_green',
# 'simply_blue',
# 'distorted_black',
# 'all_black',
# 'charcoal_grey',
# 'almost_invisible'
# 'random'
sc.image_style = 'simply_green'
# default: low
# possible values: 'low', 'medium', 'high', 'random'
sc.distortion = 'medium'
end
You can add your own style:
SimpleCaptcha.setup do |sc|
sc.image_style = 'mycaptha'
sc.add_image_style('mycaptha', [
"-background '#F4F7F8'",
"-fill '#86818B'",
"-border 1",
"-bordercolor '#E0E2E3'"])
end
You can provide the path where image_magick is installed as well:
SimpleCaptcha.setup do |sc|
sc.image_magick_path = '/usr/bin' # you can check this from console by running: which convert
end
You can provide the path where should be stored tmp files. It’s usefull when you dont have acces to /tmp (default directory)
SimpleCaptcha.setup do |sc|
sc.tmp_path = '/tmp' # or somewhere in project eg. Rails.root.join('tmp/simple_captcha').to_s, make shure directory exists
end
How to change the CSS for SimpleCaptcha DOM elements?
You can change the CSS of the SimpleCaptcha DOM elements as per your need in this file.
*/app/views/simple_captcha/_simple_captcha.erb*
View’s Examples
Controller Based Example
<%= show_simple_captcha %>
<%= show_simple_captcha(:label => "human authentication") %>
Model Based Example
<%= show_simple_captcha(:object => 'user', :label => "human authentication") %>
Model Options
message - provides the custom message on failure of captcha authentication the default is “Secret Code did not match with the Image”
add_to_base - if set to true, appends the error message to the base.
Model’s Example
class User < ActiveRecord::Base
apply_simple_captcha
end
class User < ActiveRecord::Base
apply_simple_captcha :message => "The secret Image and code were different", :add_to_base => true
end
Well, ReCaptcha will do the job and there are many tutorials on it online.
However, you have to write a correct "def create" (create method) in your controller that will pass whatever is in your form plus validate Recaptcha at the same time. Then it will work nicely.
There was one little problem with it. After I inserted ReCaptcha into my form, the form validation stopped working. However, it can be fixed with an easy code inserted into the model file:
after_validation :on => :create
(:create = is the "def create" method in your controller). It will force the form to validate the form first and then validate Recaptcha.
I've used Recaptcha in one of my PHP project. http://recaptcha.net/
According to the site, it also has plugins for Ruby (http://recaptcha.net/resources.html). Although first ruby link didn't work, next link still works. http://svn.ambethia.com/pub/rails/plugins/recaptcha/
Check it.
I've used ambethia recapchat for rails application. it most easy than other
reCAPTCHA for rails is great, in terms of functionality. However, if you require XHTML validation, RUN AWAY! This plugin does not (and probably never will) validate. I find it embarrassing that only one page on my entire site does not validate - it is the page with reCAPTCHA. If there was ANY other choice, I would take it.
if you're after a CAPTCHA that validates, and is (almost) as easy to use as reCAPTCHA, please give my SlideCAPTCHA a try. (Wrote it a few days ago, needs some tests in real-life usage.) I based its deployment process on the reCAPTCHA plugin, but you can style it with CSS.
It does require Ruby/GD, however, so if you don't have GD already, I can't promise that GD is easy to install and use!