Home > OS >  Create objects based on received data from params in Ruby on Rails
Create objects based on received data from params in Ruby on Rails

Time:11-15

Description

I am trying to create messages based on selected (via check box) users from the browser in Ruby on Rails.

Snapshot: enter image description here

Steps to reproduce

  1. My schema
ActiveRecord::Schema.define(version: 2021_11_13_142255) do

  create_table "messages", force: :cascade do |t|
    t.text "content"
    t.integer "user_id"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

  create_table "users", force: :cascade do |t|
    t.string "name"
    t.string "role"
    t.integer "phone"
    t.boolean "admin"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

end
  1. messages_controller.rb
class MessagesController < ApplicationController
  def new
    @users = User.all

    @message = Message.new(message_params)
  end

  def create
    params[:user_objs].each do |u|
      # "params.inspect" returns
          # {"authenticity_token"=>"[FILTERED]",
          #  "user_objs"=>
          #   ["{\"id\":1,\"name\":\"Alex\",\"role\":\"Engineer\",\"phone\":998943333303,\"admin\":true,\"created_at\":\"2021-11-13T14:37:54.962Z\",\"updated_at\":\"2021-11-13T14:37:54.962Z\"}",
          #    "{\"id\":2,\"name\":\"Lucy\",\"role\":\"Accountant\",\"phone\":998943333303,\"admin\":false,\"created_at\":\"2021-11-13T14:39:52.742Z\",\"updated_at\":\"2021-11-13T14:39:52.742Z\"}"],
          #  "message"=>{"content"=>"Message from the browser"},
          #  "commit"=>"Send"}
      person = JSON.parse(u)
      @message = person.messages.new(message_params)
      if @message.save
        redirect_to root_path
      else
        @users = User.all
        render :new
      end
    end
  end

  private

  def message_params
    params.permit(
        :content,
        :user_id
      )
  end
end

  1. messages => new.html.erb
<div>
    <h1>Create and send a new message!</h1>

    <%= form_for(@message) do |form| %>
        <% if @message.errors.any? %>
            <div class="alert alert-danger">
                <h5 class="fw-bold">Invalid input!</h5>
                <%= @message.errors.full_messages.each do |error| %>
                    <div><%= error %></div>
                <% end %>
            </div>
        <% end %>
        
        <% @users.each do |u| %>
            <div>
                <p><%= check_box_tag "user_objs[]", u.to_json %> <%= u.name %></p>
            </div>
        <% end %>

        <p class="mb-3">
            <%= form.label :content, class: "form-label" %>
            <%= form.text_field :content, class: "form-control", autofocus: true, placeholder: "John_D" %>
        </p>

        <p class="mb-3">
            <%= form.submit "Send", class: "btn btn-primary" %>
        </p>
    <% end %>
</div>
<%= params.inspect %>
  1. Models
# user.rb
class User < ApplicationRecord
    has_many :messages
end


# message.rb
class Message < ApplicationRecord
    belongs_to :user
end

Expected behavior

I was expecting the creation of messages for all selected users

Actual behavior

NoMethodError in MessagesController#create
undefined method `messages' for #<Hash:0x000000011fe2b420>

I tried different ways, but can't convert Ruby objects to JSON in my params user_objs[] so that I can parse it in my controller to create messages based on those selected users in the user_objs[] params.

Environment info

ruby -v
ruby 2.7.3p183 (2021-04-05 revision 6847ee089d) [arm64-darwin20]

rails -v
Rails 6.1.4.1

Thanks for any given help

  • Related