Model:
app/models/group.rb
class Group < ActiveRecord::Base
has_many :group_members
has_many :members, :through => :group_members
end
app/models/member.rb
class Member < ActiveRecord::Base
has_many :group_members
has_many :groups, :through => :group_members
end
app/models/group_members.rb
class GroupMember < ActiveRecord::Base
belongs_to :group
belongs_to :member
end
View:
app/views/groups/new.html.erb
<p class="control-group">
<%= f.label :name, :class => "control-label" %>
<p class="controls">
<%= f.text_field :name, :class => "input-xxlarge" %>
</p>
</p>
"control-label" %>
Controller:
app/controller/groups_controller.rb
def new
@group = Group.new
end
def edit
@group = Group.find(params[:id])
end
def create
# How to do?
end
def update
# How to do?
end
最后在控制器中怎么保存多个成员(members)到数据库?
이에 대한 답변은 여러 곳에 있습니다. 영어를 잘한다면 다음 Railscast를 확인해 보세요.
http://railscasts.com/episodes/196-nested-model-form-revised
Rails 4.0은 여전히 중첩 속성을 지원하며, 구체적인 문서는 여기에서 찾을 수 있습니다.
http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html