SkRoR
SkRoR

Reputation: 1199

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: enter image description here

Upvotes: 2

Views: 67

Answers (2)

Pavan
Pavan

Reputation: 33542

When you look into the params generated in the log, you will see that the message inside the course_query hash, so params[:message] should be params[:course_query][:message]

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

Upvotes: 2

Nickolay Kondratenko
Nickolay Kondratenko

Reputation: 1951

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

Upvotes: 4

Related Questions