Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5 Not able to store in database

I am not able to store the record in the database following is my code

Form Parameters

enter image description here

Controller

def create
    @sales_dailystatus_info = SalesDailystatusInfo.new(sales_dailystatus_info_params)
    @sales_dailystatus_info.user_id = current_user.id
    @project = @sales_dailystatus_info.project
    respond_to do |format|
      if @sales_dailystatus_info.save
        byebug
        format.js{}
        format.html{redirect_to dashboard_project_path(@project)}
      else
        format.js{}
        format.html{render nothing: true}
      end
    end
end

def sales_dailystatus_info_params
    params.require(:sales_dailystatus_info).permit(:user_id, :project_id, :sales_task_id, 
    :task_time, :description)
end

Model

class SalesDailystatusInfo < ActiveRecord::Base    
     belongs_to :project
     belongs_to :user, optional: true
     belongs_to :sales_task
     validates :user_id, :sales_tasks_id, :task_time, presence: true
end

You can see in the screenshot I got rollback while save.

Please help me.

Edit:

I have made the change, Now I am iterating the params and remove strong parameters. Following is my code

def create
    params[:sales_dailystatus_info].values.each do |sales_dailystatus_info|

    @sales_dailystatus_info = SalesDailystatusInfo.create(
                    project_id: sales_dailystatus_info[:project_id],
                    sales_tasks_id: sales_dailystatus_info[:sales_task_id],
                    task_time: sales_dailystatus_info[:task_time],
                    description: sales_dailystatus_info[:description],
                    user_id: current_user.id
    );  
    byebug       
  end      

  respond_to do |format|
    format.js{}
    format.html{render nothing: true}
    end
end

still not able to save it. Give me error Sales task must exist.

like image 826
urjit on rails Avatar asked Jan 20 '20 18:01

urjit on rails


Video Answer


2 Answers

Looking at your logs, it looks like your are submitting two SalesDailyStatusInfo:

{... 'sales_daily_status_info" => { "0" => {"project_id" => ...}, "1" => { "project_id" => ... } } }  

You don't allow those keys in your params sanitizer, hence the Unpermitted parameters: :0, :1. The result is that your don't whitelist any params you submit and the params hash is empty, your model validations fail.

In order for this to work you either need to send only one project at a time or loop through your params to create both SalesDailyStatusInfo.

Add the frontend form code to your question if you need further help.

Hope it helps !

like image 131
Vincent Rolea Avatar answered Oct 19 '22 16:10

Vincent Rolea


Looks like your record is not valid. You validate presence of the user_id but it's not sent. Instead of rendering nothing try to render @sales_dailystatus_info.errors.messages

like image 21
Kamil Gwóźdź Avatar answered Oct 19 '22 17:10

Kamil Gwóźdź