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| %>
 



 

转载于:https://www.cnblogs.com/Akishimo/p/4360303.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值