Rails 在javascript中使用ruby对象
1.在javascript中使用ruby简单对象
如,需要将ruby对象转换成javascript的简单变量:
<%= javascript_tag do %>
url = '<%= j products_url %>';
<% end %>
此时的<%= %>是由引号包裹的。rails的j方法是为了正确地转义ruby对象从而嵌入javascript中。
Read on →如,需要将ruby对象转换成javascript的简单变量:
<%= javascript_tag do %>
url = '<%= j products_url %>';
<% end %>
此时的<%= %>是由引号包裹的。rails的j方法是为了正确地转义ruby对象从而嵌入javascript中。
Read on →rails URL路由的最权威文档当然是其官方站点Rails routing from the outside in,我这里只提几个文档中常用的要点。
由resources建立的资源,是rails中最常见的路由方式,不用多说。
resources :photos
Read on →
一步步安装使用jquery-file-upload
Read on →若存在如下Post model:
class Post < ActiveRecord::Base
belongs_to :author
has_many :comments
end
使用下面的循环加载数据时产生了N+1查询问题:
Post.all.each do |post|
puts "Post: " + post.title
puts "Written by: " + post.author.name
puts "Last comment on: " + post.comments.first.created_on
end
Read on →
以经典的customer-order为例
1 2 |
|
查看order的migration文件,rails自动为我们添加了index:
1 2 3 4 5 6 7 8 9 |
|
在gemfile中添加一行:
gem 'devise'
执行bundle install后,需要安装devise到工程:
rails generate devise:install
创建验证用户model,通常用user,也可以使用其他名称:
rails generate devise user
rake db:migrate
Read on →
Thread.new do
3.times do
sleep 3
puts "Thread #{Thread.current.object_id} running..."
end
end
ruby使用在Thread.new创建线程,线程创建后立即返回,线程也同时开始执行。ruby线程可以在创建块中使用外部变量,也可以使用本地变量,值变量在线程内部保存的是本地副本,而引用变量保存的是一个本地引用。
class Book
attr_accessor :name
end
num = 0
count = 0
book = Book.new
book.name = 'ybur'
puts "main Thread=#{num} count=#{count} book=#{book.name}"
t.Thread.new(num,book) do |n,b|
n+=1
count+=1
b.name.reverse!
puts "new Thread:num=#{n} count=#{count} book=#{b.name}"
end
t.join
puts "main Thread:num=#{num} count=#{count} book=#{book.name}"
#=>main Thread:num=0 count=0 book=ybur
#=>new Thread:num=1 count=1 book=ruby
#=>main Thread:num=0 count=1 book=ruby
Read on →
如图所示,在demo数据库中有customers和orders两张表。一个customer有多个order,一个order属于一个customer,是一个1:n关系。
建立数据表
$ rails g model customer name:string
$ rails g model order customer_id:integer order_date:datetime
$ rails g model rake db:migrate