如何在一个提交中添加两个数据库表中的详细信息

时间:2015-09-28 10:18:21

标签: ruby-on-rails

我有3个表:coachescategories以及联接表categories_coaches,提交时我想将category_idcoach_id存储在联接表中categories_coaches表格中的nameemailuniversitybatchphonecoach。该怎么做?

现在细节存储在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 %>

1 个答案:

答案 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的做法是正确的:

enter image description here

实现这一目标的重要性在于,每次CRUD CoachCategory个对象,您都可以通过{{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