rails 3 multiple language for any user - ruby

I want my app has multiple languages. To do this, I read railscasts #138
But there, the writer put a language column to User model and thus users can see pages only in their language as I understand right. But I want my website can be seen in any language by any user just like usual.
How can this be done?

I have solved. I added to controllers/application_controller.rb this:
before_filter :set_locale
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
private
def default_url_options(options={})
logger.debug "default_url_options is passed options: #{options.inspect}\n"
{ :locale => I18n.locale }
end
Then I added this to views/layouts/_header.html.erb:
<li><% if I18n.locale == I18n.default_locale %>
<%= link_to "Türkçe", :locale=>'tr'%>
<% else %>
<%= link_to "English", :locale=>'en'%>
<%end%></li>
Then to config/routes.rb this:
scope "(:locale)", :locale => /en|tr/ do # at the beginning
match '/home' , to: 'static_pages#home'
match '/help' , to: 'static_pages#help'
match '/about' , to: 'static_pages#about'
.....
end
Thats it!

You might want to take a look at this great Rails guide.

in addition to #Pierre-Louis answer, you can look at globalize3 gem

Related

Rails 4 search bar

I'm trying to create a search bar in my Rails 4 app. I'm my user db has 'name' and 'email' columns for the user's - I want users to be able to search for other users by name or id.
I'm currently getting this:
ActiveRecord::RecordNotFound in UsersController#index
Couldn't find all Users with 'id': (all, {:conditions=>["name LIKE ?", "%hi#example.com%"]}) (found 0 results, but was looking for 2)
Does anyone know what I'm doing wrong? I've looked at railscasts and a few forums etc but cant get past this point at the moment.
index.html.erb:
<% form_tag users_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
model/user.rb:
def self.search(search)
if search
find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
else
find(:all)
end
end
users_controller.rb:
def index
#users = User.search(params[:search])
end
routes.rb:
get 'search' => 'users#index'
Are you using Rails 4? find(:all, ...) is the old way of doing things. find only takes ids now. Use:
def self.search(search)
if search.present?
where('name LIKE ?', "%#{search}%")
else
where(true)
end
end
Also present? will test against both nil and blank. Keep in mind that LIKE can be really slow depending on your database.
Searching in rails
By default rails doesn't support full text searching .Activerecord finder always find a record using the primary key ie. id.
Hence , we need some other gems or applications like sunspot, elasticsearch etc..
i'll show you using Sunspot solr here ..
in the gem file of your application just add the following code...
.
gem 'sunspot_rails'
group :development do
gem 'sunspot_solr'
end
and in terminal use
bundle install
rails g sunspot_rails:install
this will add solr and creates config/sunspot.yml file
rake sunspot:solr:start
rake sunspot:reindex
edit the user.rb lile in models
app/model/user.rb
Class User < ActiveRecord::Base
searchable do
text :name, :email
end
end
in app/controller/users_controller.rb
and then add in index function
def index
#search = User.search do
fulltext params[:search]
end
#users = search.results
end
Make a form to take a user input
<%= label_tag(:search, "Search for:") %>
<%= text_field_tag(:search) %>
<%= submit_tag("Search") %>
<% end %>

Sinatra App Not Using Erb in Links

The problem I'm having is that Sinatra apps don't always seem to show my ERB when it is used in some specific context of hyperlinks. I have no idea how much is relevant to show for this question, so I'll do the best I can .Basically, I have a file in my Sinatra app called book_show.erb. It has the following line:
<p>Edit Book</p>
However, when that link is rendered in the browser, it links like this:
http://localhost:9292/books/#{#book.id}/edit
The #{#book.id} was not replaced with the actual ID value. There is a #book object and I do use it in other contexts in that very same file. For example:
<h1><%= #book.series %></h2>
<h2><%= #book.title %></h2>
<h3>Timeframe:</h3>
<p><%= #book.timeframe %></p>
I don't even know if my routes would make a difference here for diagnosing this but all of the relevant routes for my books functionality are:
get '/books' do
#title = 'Book Database'
#books = Book.all
erb :books
end
get '/books/new' do
#book = Book.new
erb :book_add
end
get '/books/:id' do
#book = Book.get(params[:id])
erb :book_show
end
post '/books' do
book = Book.create(params[:book])
redirect to("/books/#{book.id}")
end
I don't know what else to show to help diagnose this problem. I'm hoping someone sees something terribly obvious that I'm missing.
Adding a book to the database works just fine; it's only that edit link that I can't get to work correctly -- and that would seem to be pure HTML/ERB. In order to test it, I also added this line to the page:
<p>Testing: <%= "/books/#{#book.id}/edit" %>
That came back and returned this text:
Testing: /books/4/edit
So I know the ID is getting stored. It has to be something to do with the hyperlink but I can find nothing useful on Sinatra that helps at all with this.
ERB template does not behave like a ruby string - you need to explicitly tell it you exit the 'template' part into the 'logic' part. It looks very odd when it comes to attributes:
<p>Edit Book</p>
You could use link_to helpers to make it look better:
link_to('Edit Book', controller: 'books', action: 'edit', id: #book.id)

How to upload a file temporarily in Rails 3?

I'm creating CSV-upload functionality for a site of mine.
I'm looking to upload a file, parse it, and then dispose of it.
I know I can upload and save a file using Paperclip, but that seems a bit like overkill.
All I need to do is parse the uploaded file and never save it.
How would I go about doing this in Rails 3?
Note: I'd prefer to do the uploading manually without using an external gem so I can learn how to process works, but any suggestions are welcome.
Thanks!
Use the file_field helper in your form, then in your controller you can use File.Write and File.read to save the file.
E.g. View
<%= form_for #ticket do |f| %>
<%= f.file_field :uploaded_file %>
<% end %>
Controller
def upload
uploaded = params[:ticket][:uploaded_file]
File.open(<insert_filename_here>, 'w') do |file|
file.write(uploaded.read)
end
end
Edit: Just saw #klochner's comment, that link says pretty much what I have said so follow that: RubyOnRails Guides: Uploading Files.
Paste this in your model
def parse_file
File.open(uploaded/file/path, 'w') do |f| # Feed path that user gives in some way
## Parse here
end
end
this in view
<%=form_for #page, :multipart => true do |f|%>
<ul><li><%= f.label :file%></li>
<li><%= f.file_field :uploaded_file%></li></ul>
<%end%>
Let me know if this works. If it fails figure out a way to feed path of uploaded_file in parse_file method (the definite way which will work is storing file location in db and picking up from there, but it is not the right way to do this thing). Otherwise, I guess it should work.
Complete Example
Take, for example, uploading an import file containing contacts. You don't need to store this import file, just process it and discard it.
Routes
routes.rb
resources :contacts do
collection do
get 'import/new', to: :new_import # import_new_contacts_path
post :import, on: :collection # import_contacts_path
end
end
Form
views/contacts/new_import.html.erb
<%= form_for #contacts, url: import_contacts_path, html: { multipart: true } do |f| %>
<%= f.file_field :import_file %>
<% end %>
Controller
controllers/contacts_controller.rb
def new_import
end
def import
begin
Contact.import( params[:contacts][:import_file] )
flash[:success] = "<strong>Contacts Imported!</strong>"
redirect_to contacts_path
rescue => exception
flash[:error] = "There was a problem importing that contacts file.<br>
<strong>#{exception.message}</strong><br>"
redirect_to import_new_contacts_path
end
end
Contact Model
models/contact.rb
def import import_file
File.foreach( import_file.path ).with_index do |line, index|
# Process each line.
# For any errors just raise an error with a message like this:
# raise "There is a duplicate in row #{index + 1}."
# And your controller will redirect the user and show a flash message.
end
end

Using Padrino form helpers and formbuilder - getting started

I've jumped into learning Ruby by going straight to Padrino with Haml.
Most of the Padrino documentation assumes a high-level of knowledge of Ruby/Sinatra etc...
I am looking for samples that I can browse to see how things work. One specific scenario is doing a simple form. On my main (index) page I want a "sign up" edit box with button.
#app.rb
...
get :index, :map => "/" do
#user = "test"
haml: index
end
get :signup, :map => "/signup" do
render :haml, "%p email:" + params[:email]
end
...
In my view:
#index.haml
...
#signup
-form_for #user, '/signup', :id => 'signup' do |f|
= f.text_field_block :email
= f.submit_block "Sign up!", :class => 'button'
...
This does not work. The render in (/signup) never does anything.
Note, I know that I need to define my model etc...; but I'm building to to that in my learning.
Instead of just telling me what I'm doing wrong here, what I'd really like is a fairly complete Padrino sample app that uses forms (the blog sample only covers a small part of Padrino's surface area).
Where can I find tons of great Padrino samples? :-)
EDIT
The answer below was helpful in pointing me at more samples. But I'm still not finding any joy with what's wrong with my code above.
I've changed this slightly in my hacking and I'm still not getting the :email param passed correctly:
#index.haml
...
#signup
- form_for :User, url(:signup, :create), :method => 'post' do |f|
= f.text_field_block :email
= f.submit_block "Sign up!"
...
#signup.rb
...
post :create do
#user = User.new(params[:email])
...
end
EDIT Added Model:
#user.rb
class User
include DataMapper::Resource
property :id, Serial
property :name, String
property :email, String
...
end
When this runs, params[:email] is always nil. I've compared this to bunches of other samples and I can't see what the heck I'm doing wrong. Help!
You can browse some example sites here: https://github.com/padrino/padrino-framework/wiki/Projects-using-Padrino
Or you can browse sources of padrinorb.com here: https://github.com/padrino/padrino-web
The best way also is to generate admin: padrino g admin where you should see how forms works.
The tag form perform by default post actions unless you specify :method => :get|:put|:delete so in your controller you must change :get into :post
post :signup, :map => "/signup" do ...
Since you are using form_for :user params are in params[:user] so to get email you need to puts params[:user][:email]

Passing parameters to erb view

I'm trying to pass parameters to an erb view using Ruby and Sinatra.
For example, I can do:
get '/hello/:name' do
"Hello #{params[:name]}!"
end
How do I pass :name to the view?
get '/hello/:name' do
erb :hello
end
And how do I read the parameters inside view/hello.erb?
Thanks!
just pass the :locals to the erb() in your routes:
get '/hello/:name' do
erb :hello, :locals => {:name => params[:name]}
end
and then just use it in the views/hello.erb:
Hello <%= name %>
(tested on sinatra 1.2.6)
Not sure if this is the best way, but it worked:
get '/hello/:name' do
#name = params[:name]
erb :hello
end
Then, I can access :name in hello.erb using the variable #name
get '/hello/:name' do
"Hello #{params[:name]}!"
end
You cannot do this in routes.
You want to set the params in the controller.
app/controllers/some_controller.rb
def index
params[:name] = "Codeglot"
params[:name] = "iPhone"
params[:name] = "Mac Book"
end
app/views/index.html.erb
<%= params[:name] %>
<%= params[:phone] %>
<%= params[:computer] %>

Resources