建立新項目:rails new meetup -d mysqlhtml
migrate數據庫:rake db:create db:migratemysql
生成controller:rails generate controller welcome
sql
生成model:rails g model event name:string description:text is_public:boolean capacity:integer
數據庫
查看路由: rake routes數組
rake幫助查看:rake -Tless
scaffold生成簡易crud程序命令:rails g scaffold person name:string bio:text birthday:date
ui
生成新的欄位:rails g migration add_status_to_events
url
行數統計:rake stats
code
查看log:tail -f log/development.logorm
一對多:
建立、刪除、查找、
u = User.first
a = Article.new(...........)
a.user_id = u.id
a.saveclass Category < ActiveRecord::Base has_many :events end class Event < ActiveRecord::Base belongs_to :category # ... end
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
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| %>