ruby - rails 4 多對多的控制器和視圖怎麼實現?
迷茫
迷茫 2017-04-21 11:16:02
0
1
775

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)到數據庫?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回覆(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

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板