我有3个表:coaches
,categories
以及联接表categories_coaches
,提交时我想将category_id
和coach_id
存储在联接表中categories_coaches
表格中的name
和email
,university
,batch
,phone
,coach
。该怎么做?
现在细节存储在coach表中,但不存储在连接表
中请帮我解决这个问题。
coach.rb
class Coach < ActiveRecord::Base
has_and_belongs_to_many :categories
end
category.rb
class Category < ActiveRecord::Base
belongs_to :coach
end
registrationcontroller.erb
class Coaches::RegistrationsController < Devise::RegistrationsController
def new
@individual=@individual ||= Coach.new
super
end
def create
build_resource sign_up_params
@individual=@individual ||= Coach.new
super
end
private
def sign_up_params
params.require(:coach).permit(:name, :email, :university, :batch, :linkedin_url, :code, :phone,category_ids: []
)
end
end
查看页面
<%= simple_form_for(@individual, as: :coach, url: registration_path(:coach)) do |f| %>
<%= f.input :name, required: true, %>
<%= f.input :university %>
<%= f.input :batch %>
<%= f.input :email%>
<%= f.input :phone%>
<div class="category-scroll">
<% Category.all.each do |c| %>
<% if c.parent_id != nil %>
<div class="category-left">
<%= check_box_tag "category_ids[]", c.id, false, :id => "category_ids_#{c.id}" %>
<%= c.name %>
</div>
<% else %>
<b><%= c.name %></b>
<% end %>
<% end %>
</div>
<div class="form-group">
<%= f.button :submit, "SUBMIT", class: "apply-continue_form" %
<% end %>
答案 0 :(得分:0)
你所提到的听起来像has_and_belongs_to_many
与我的关系。
我将详细说明你应该做什么,以及该协会的基本机制:
#app/models/coach.rb
class Coach < ActiveRecord::Base
has_and_belongs_to_many :categories
end
#app/models/category.rb
class Category < ActiveRecord::Base
has_and_belongs_to_many :coaches
end
这与has_many :through
关系相反,为你做了大部分的工作。您设置join_table
的做法是正确的:
实现这一目标的重要性在于,每次CRUD
Coach
或Category
个对象,您都可以通过{{1}访问相关数据分别是}和:categories
方法。
因此,您可以像这样填充数据:
:coaches
这将允许您进行以下视图:
#config/routes.rb
resources :coaches #-> url.com/coaches/new
#app/controllers/coaches_controller.rb
class CoachesController < ApplicationController
def index
@coaches = Coach.all
end
def new
@coach = Coach.new
end
def create
@coach = Coach.new coach_params
end
private
def coach_params
params.require(:coach).permit(:name, :email, :university, :batch, :phone, :categories)
end
end