ruby - rails 4 多对多的控制器和视图怎么实现?

【字号: 日期:2022-10-23浏览:24作者:雯心

问题描述

Model:

app/models/group.rb

class Group < ActiveRecord::Base has_many :group_members has_many :members, :through => :group_membersend

app/models/member.rb

class Member < ActiveRecord::Base has_many :group_members has_many :groups, :through => :group_membersend

app/models/group_members.rb

class GroupMember < ActiveRecord::Base belongs_to :group belongs_to :memberend

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.newenddef edit @group = Group.find(params[:id])enddef create # How to do?enddef update # How to do?end

最后在控制器中怎么保存多个成员(members)到数据库?

问题解答

回答1:

这个好多地方都有解答, 如果英文好的话,可以看看这一个Railscasts:

http://railscasts.com/episodes/196-nested-model-form-revised

Rails 4.0依然支持Nested Attributes, 具体的文档可以看这里。

http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

相关文章: