rails 命令
創(chuàng)建新項(xiàng)目:rails new meetup -d mysql
migrate數(shù)據(jù)庫(kù):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生成簡(jiǎn)易crud程序命令:rails g scaffold person name:string bio:text birthday:date
生成新的欄位:rails g migration add_status_to_events
行數(shù)統(tǒng)計(jì):rake stats
查看log:tail -f log/development.log
?
一對(duì)多:
class Category < ActiveRecord::Basehas_many :events endclass Event < ActiveRecord::Basebelongs_to :category# ... end創(chuàng)建、刪除、查找、
u = User.first
a = Article.new(...........)
a.user_id = u.id
a.save e = Event.first e.attendees.destroy_all # 一筆一筆刪除 e 的 attendee,並觸發(fā) attendee 的 destroy 回呼 e.attendees.delete_all # 一次砍掉 e 的所有 attendees,不會(huì)觸發(fā)個(gè)別 attendee 的 destroy 回呼
a = e.attendees.find(3) attendees = e.attendees.where( :name => 'ihower' ) #查出來(lái)的是數(shù)組
一對(duì)一: class Event < ActiveRecord::Basehas_one :location # 單數(shù)#... endclass Location < ActiveRecord::Basebelongs_to :event # 單數(shù) end
多對(duì)多 class Event < ActiveRecord::Basehas_many :event_groupshipshas_many :groups, :through => :event_groupships endclass EventGroupship < ActiveRecord::Basebelongs_to :eventbelongs_to :group endclass Group < ActiveRecord::Basehas_many :event_groupshipshas_many :events, :through => :event_groupships end 一對(duì)多創(chuàng)建 @attendee = @event.attendees.build
一對(duì)多路由: resources :events doresources :attendees, :controller => 'event_attendees' end 一對(duì)一創(chuàng)建 @location = @event.build_location
一對(duì)一路由
?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_paramsparams.require(:event).permit(:name, :description, :category_id, :location_attributes => [:name] ) end提交表單改成 <%= form_for setup_event(@event), :url => events_path do |f| %> ?
?
轉(zhuǎn)載于:https://www.cnblogs.com/Akishimo/p/4360303.html
總結(jié)
- 上一篇: PHP中的中文截取乱码问题_gb2312
- 下一篇: [问题解决]同时显示多个Notifica