如何在Ruby on Rails中传递控制器参数

时间:2015-09-24 12:52:48

标签: ruby-on-rails

当我写信息并按下发送选项时, 我想将student_idcoach_idmessage存储到数据库中。正在保存student_idcoach_id,但未保存message字段。它在数据库中显示为null。我该如何解决这个问题?

感谢任何帮助。

控制器文件:

class CourseQueriesController <ApplicationController
  def index 
    @course_query = CourseQuery.new
  end

  def create
    # @course_query = CourseQuery.new(course_query_params)
    @course_query = CourseQuery.where(student_id: current_student.id, coach_id: "2", message: params[:message]).first_or_create 
    if @course_query.save
      redirect_to course_queries_path, notice: 'Query was successfully send.'
    else
      render :new
    end
  end

  private

  def set_course_query
    @course_query = CourseQuery.find(params[:id])
  end

  # def course_query_params
  #   params[:course_query].permit(:message)
  # end
end

模型/ course_query.rb:

class CourseQuery < ActiveRecord::Base
  belongs_to :student
  belongs_to :coach
end

查看/ course_query / index.html.erb:

<%= simple_form_for (@course_query) do |f| %>
<%= f.button :submit , "Send or press enter"%>
<%= f.input :message %>
<% end %>

database / course_queries: enter image description here

2 个答案:

答案 0 :(得分:4)

您似乎不允许:course_query

尝试以下列方式允许你的参数:

 def course_query_params
   params.require(:course_query).permit(:message)
 end

但是根据你通过params(params[:message])的第二种方式,我认为你有一些不同的params结构。所以尝试另一个:

 def course_query_params
   params.permit(:message)
 end

答案 1 :(得分:2)

当您查看日志中生成的params时,您会在message哈希中看到course_query,因此params[:message]应为params[:course_query][:message]

@course_query = CourseQuery.where(student_id: current_student.id, coach_id: "2", message: params[:course_query][:message]).first_or_create