lundi 17 février 2020

Rails Pass/Send variable from model to controller

I have some data processed from CSV file and stored in a variable. I need to send this attribute to controller on create and update a record.

Model.rb

attr_accessor :unique_messages
validate :read_csv_file

def read_csv_file
  if self.csv_file.present?
    csv_data = CSV.read(self.csv_file.path, :headers=>false)
    unique_messages = csv_data.to_h
  end
end

Controller.rb

def create
    @message_notice = MessageNotice.new(notice_attributes)

    if @message_notice.save
      flash[:success] = 'success'
    end

def notice_attributes
    attributes = params.require(:message_notice).permit(:message,:user_ids, :csv_file, :unique_messages)
end

I debugged using binding.pry and during the create/update method call before saving the params, validate :read_csv_file is executed successfully and i can see the values for variable :unique_messages on Model.rb. I need to pass that :unique_messages to controller params attribute to save in database. Now :unique_messages attribute on controller is always empty. Can any one help me how to pass the value of variable from model to controller.

Thank you.

Aucun commentaire:

Enregistrer un commentaire