Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
Javascript rendering [object Object] as string data type

I've been trying to solve this for a while now. Here's my JS class:

class Comment {
        constructor(comment) {
            
            this.id = comment.id
            this.comment = comment
        }
    
        static createComment(e){
            e.preventDefault()
            const commentMessage = e.target.children[0].value
            const commentList = e.target.previousElementSibling
            
    
            Comment.submitComment(commentMessage, commentList)
            e.target.reset()
        }
    
        renderComment(commentList){
            const p = document.createElement('p')
            p.dataset.id = this.id
            p.innerText = "- " + this.comment + " "
        }
    
        static submitComment(commentMessage, commentList){
    
            fetch(commentsURL, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "Accept": "application/json",
                },
                body: JSON.stringify({
                    comment: commentMessage
                }),
            })
            .then(response => response.json())
            .then(comment => {
                let newComment = new Comment(comment)
                newComment.renderComment(commentList)
            })
        
        }
}```

Which returns the following error from my Rails API:

"NoMethodError (undefined method `permit' for "comment":String):

app/controllers/comments_controller.rb:24:in comment_params' app/controllers/comments_controller.rb:8:in create'"

And here's that controller:

class CommentsController < ApplicationController
    def index
        comments = Comment.all
        render json: comments
    end

    def create
        comment = Comment.new(comment_params)
        if comment.save
            render json: comment
        else
            render json: {errors: comment.errors.full_messages}
        end
    end

    private

    def comment_params
        params.require(:comment).permit(:comment)
    end
end

Any help is welcome and I'll try to keep it as clear as needed.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Looks like the ruby controller is trying to do an operation to the return string which is not a valid method. Where did you get the .permit() from? Maybe ask in a ruby forum?

The reason it is returning [Object object] is because you are expecting a json object in your fetch request. You would usually just render the string that is returned from one of the values in the json object, but in this case it is an error object.

about 4 years ago · Juan Pablo Isaza Relatório

0

You post your comments with this:

fetch(commentsURL, {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        "Accept": "application/json",
    },
    body: JSON.stringify({
        comment: commentMessage
    }),
})

That means that you're sending JSON like { "comment": "Comment text goes here..." } to Rails.

Then over in Rails you try to unpack that with this:

params.require(:comment).permit(:comment)

That's says "the parameters must have comment field and within that comment field look for the comment field". So that's looking for JSON like this:

{
  "comment": {
    "comment": "Comment text goes here.."
  }
}

So change your JSON to match your parameter parsing:

JSON.stringify({
  comment: { comment: commentMessage }
})

or change your parameter parsing to match your JSON:

params.permit(:comment)
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda