I'm trying to use postman for submitting a form in rails. I have these parameters

{
    "book": {
        "title": "rrewr",
        "media": {
            "name": "hello",
            "format": "jpg"
        }
    }
}

When submitting this parameters. I have these code for creating book in my controller

class Admin::BookController < ApplicationController
  def create
    @book = Book.new(book_params)

    if(@book.save)
     # redirect_to @post
    end
  end

  private def book_params
    params.require(:book).permit(:title, :media => [:name, :format])
  end
end

I have one to one relationship with books to media. But when I receive the request. I got this error <ActiveRecord::AssociationTypeMismatch: Media(#70348614328640) expected, got {\"name\"=>\"hello\", \"format\"=>\"jpg\"} which is an instance of ActiveSupport::HashWithIndifferentAccess(#47385709875460)>

I already search this in rails documentation and even in google but I can't find one that same problem of mine. I have this model for book and media

class Book < ApplicationRecord
   belongs_to :media
end

class Media < ApplicationRecord
    has_one :book
end

I have these migrations. Please Correct me If I did wrong. I can't identify which part of my code is wrong or I have a missing code to add.

class CreateBooks < ActiveRecord::Migration[5.2]
  def change
    create_table :books do |t|
      t.string :title
      t.references :media, index: true, foreign_key: true

      t.timestamps
    end
  end
end

class CreateMedia < ActiveRecord::Migration[5.2]
  def change
    create_table :media do |t|
      t.string :name
      t.string :format

      t.timestamps
    end
  end
end

1 Answers

0
Usar On Best Solutions

As you are trying to create book with media. so please try this:

class Admin::BookController < ApplicationController
  def create
    @media = Media.new(media_params)
    ActiveRecord::Base.transaction do
      @media.save!
      @media.create_book!(book_params)

      # redirect_to @post
    end
  end

  private
  def book_params
    params.require(:book).permit(:title)
  end
  def media_params
    params.require(:media).permit(:name, :format)
  end
end

For postman, try passing parameter like this:

 media: {
    name: '',
    format: ''
  },
  book: {
    title: ''
  }
}