无法获得要在课程中显示的位置

时间:2019-05-17 13:11:14

标签: ruby-on-rails ruby ruby-on-rails-5

我是红宝石的新手,我试图获取我在表单中分配的locations选项,以显示在course显示页面上

当我在Rails控制台中运行命令course.locations= [location]时,它工作正常,但是如何在没有为每个course运行此命令的情况下显示它?我在某处错过了一步吗?

模型-course.rb

has_and_belongs_to_many :locations

模型-location.rb

has_and_belongs_to_many :courses

show.html.erb

<% @course.locations.each do |location| %>
    <%= link_to location.name, courses_path(:id => location.id, :table => "Location") %>
<% end %>

<%= @course.description %>

课程管理员

class CoursesController < ApplicationController
  def new
     @course = Course.new
  end

  def index
    @course = Course.all
  end

  def show
   @course = Course.find(params[:id])
  end

  def create

    @course = Course.new(course_perms)

    if @course.valid?
      @course.save
      flash[:success] = "Category Made Successfully - #{@course.name}"
      redirect_to @course
    else
      render 'new'
    end
  end

  def course_perms
    params.require(:course).permit([:name, :desc, :locations => [], :categories => []])
  end
end

表格

<%= form_for(@course) do |f| %>

  <%= f.label :name %>
  <%= f.text_field :name, class: 'form-control' %>

  <%= f.label :desc %>
  <%= f.text_field :desc, class: 'form-control' %>

  <%= f.label :locations %>
  <%= f.select :locations, options_from_collection_for_select(@locations, :id, :name, course.locations.ids)%>

  <%= f.label :categories %>
  <%= f.select :categories, options_from_collection_for_select(@categories, :id, :name)%>

  <%= f.submit yield(:button_text), class: "btn btn-primary" %>
<% end %> ```

1 个答案:

答案 0 :(得分:1)

您需要检查服务器控制台,在那里您可能已经看到update / save操作可能会给您一个parameter not allowed错误。这是因为您将错误的参数列入了白名单:

class CoursesController < ApplicationController
  def new
     @course = Course.new
  end

  def index
    @course = Course.all
  end

  def show
   @course = Course.find(params[:id])
  end

  def create

    @course = Course.new(course_perms)

    if @course.valid?
      @course.save
      flash[:success] = "Category Made Successfully - #{@course.name}"
      redirect_to @course
    else
      render 'new'
    end
  end

  #also make this method private
  private

  def course_perms
    params.require(:course).permit([:name, :desc, :location_ids => [], :category_ids => []])
  end
end