rails 命令
创建新项目:rails new meetup -d mysql
migrate数据库:rake db:create db:migrate
生成controller:rails generate controller welcome
生成model:rails g model event name:string description:text is_public:boolean capacity:integer
查看路由: rake routes
rake帮助查看:rake -T
scaffold生成简易crud程序命令:rails g scaffold person name:string bio:text birthday:date
生成新的栏位:rails g migration add_status_to_events
行数统计:rake stats
查看log:tail -f log/development.log
一对多:
class Category < ActiveRecord::Base has_many :events end class Event < ActiveRecord::Base belongs_to :category # ... end
创建、删除、查找、
u = User.first
a = Article.new(...........)
a.user_id = u.id
a.save
e = Event.first
e.attendees.destroy_all # 一筆一筆刪除 e 的 attendee,並觸發 attendee 的 destroy 回呼
e.attendees.delete_all # 一次砍掉 e 的所有 attendees,不會觸發個別 attendee 的 destroy 回呼
a = e.attendees.find(3)
attendees = e.attendees.where( :name => 'ihower' ) #查出来的是数组
一对一:
class Event < ActiveRecord::Base
has_one :location # 單數
#...
end
class Location < ActiveRecord::Base
belongs_to :event # 單數
end
多对多
class Event < ActiveRecord::Base
has_many :event_groupships
has_many :groups, :through => :event_groupships
end
class EventGroupship < ActiveRecord::Base
belongs_to :event
belongs_to :group
end
class Group < ActiveRecord::Base
has_many :event_groupships
has_many :events, :through => :event_groupships
end
一对多创建
@attendee = @event.attendees.build
一对多路由:
resources :events do
resources :attendees, :controller => 'event_attendees'
end
一对一创建@location = @event.build_location
一对一路由
resources :user do
resource :role, :controller => 'user_role'
end
Nested Model
user的model里加上 accepts_nested_attributes_for :role, :allow_destroy => true, :reject_if => :all_blank
user 的new.html里加上
<%= f.fields_for :role do |role_form| %>
<p>
<%= role_form.label :name, "Role Name" %>
<%= role_form.text_field :name %>
<% unless role_form.object.new_record? %>
<%= role_form.label :_destroy, 'Remove:' %>
<%= role_form.check_box :_destroy %>
<% end %>
</p>
<% end %>
user的helper加上
def setup_user(user)
user.build_role unless user.role
user
end
user的controller改成
def event_params params.require(:event).permit(:name, :description, :category_id, :location_attributes => [:name] ) end
提交表单改成
<%= form_for setup_event(@event), :url => events_path do |f| %>