使用单个控制器创建多个表

时间:2014-05-09 07:51:32

标签: ruby-on-rails

对于这个rails非常新。我有类控制器。使用类控制器我必须创建多个table.how来创建它吗?请帮助。这是我的类控制器。

ClassesController < ApplicationController
  before_filter :is_login?
  layout :get_layout

  def new
    @instructor = Instructor.new
    @insfirst = InsFirst.new
    @inssecond = InsSecond.new
  end


  def find
    @instructor = Instructor.new
    @insfirst = InsFirst.new
  end



  def create
    @instructor = Instructor.new(params[:instructor])
    @insfirst = InsFirst.new(params[:insfirst])
    @inssecond = InsSecond.new(params[:inssecond])
    if @instructor.save
      flash[:notice] = "class has been created successfully"
      redirect_to classes_path
    else if @insfirst.save
        flash[:notice] = "class has been created successfully"
         redirect_to classes_path

    end
    render :new
    end
  end


  def index
    @instructors = Instructor.all
    puts "=============="

    @insfirsts = InsFirst.all
    @insseconds = InsSecond.all
  end

1 个答案:

答案 0 :(得分:0)

既然你是新人,我会给你一些帮助:

  

我必须创建多个表

You don't create tables in Rails。你添加&amp;从表中读取。这些表只是存储数据的地方。你真正要问的是I need to create *records* in the tables

以下是:

def create
    @instructor = Instructor.new(instructor_params)
    @insfirst = InsFirst.new(insfirst_params)
    @inssecond = InsSecond.new(inssecond_params)
    if @instructor.save
      flash[:notice] = "class has been created successfully"
      redirect_to classes_path
    else if @insfirst.save
        flash[:notice] = "class has been created successfully"
    end
    redirect_to classes_path
end

private

def instructor_params
    params.require(:class).permit(instructor: [])
end

def insfirst_params
    params.require(:class).permit(insfirst: [])
end

def inssecond_params
    params.require(:class).permit(inssecond: [])
end

这假设您传递了一个类似于下划线的参数:

params: {
   class: {
      instructor: [],
      insfirst: [],
      inssecond: []
   }
}

其他东西:

  def index
    @instructors = Instructor.all
    puts "=============="

    @insfirsts = InsFirst.all
    @insseconds = InsSecond.all
  end

请勿在控制器中使用puts。 Rails是MVC - 这意味着您只需使用控制器将数据传递到前端视图。您将在视图中使用HTML标记来处理您已包含的分隔符:

#app/controllers/classes_controller.rb
def index
   @instructors = Instructor.all
   @insfirsts   = InsFirst.all
   @insseconds  = InsSecond.all
end

#app/views/classes/index.html.erb
<%= @instructors.inspect() %>
==============
<%= @insfirsts.inspect() %>
<%= @insseconds.inspect() %>