简体   繁体   中英

How to pass controller parameters in Ruby on Rails

When I write a message and when pressing the send option, I want to store student_id , coach_id and message to the database. student_id and coach_id are being saved, but the message field is not being saved. It shows null in the database. How do I fix this?

Any help is appreciated.

Controller file:

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

model/course_query.rb:

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

view/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: 在此处输入图片说明

It seems you didn't permit :course_query .

Try to permit your params the following way:

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

But according to the 2nd way you pass params ( params[:message] ) I think you have a bit different params structure. So try another one:

 def course_query_params
   params.permit(:message)
 end

当您查看日志中生成的params ,您会看到course_query哈希内的message ,因此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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM