Rails 4 form - no implicit conversion of Model into String

前端 未结 2 1534

After adding a helper method and edit my form, I\'m getting this error

TypeError in Posts#create

Showing /Users/jim/project/test/app/views/posts/_form.html.erb          


        
相关标签:
2条回答
  • 2021-01-22 00:43

    I have found the problem thanks to @sissy comment.

    I should pass @question = cookies[:question] instead of @question = Question.where(id: params[:post][:question_id]).first in my create action of my posts controller

    Thanks everyone for your help.

    0 讨论(0)
  • 2021-01-22 00:51

    Your helper seems suspicious to me -- you're passing a Ruby object and trying to parse it as JSON

    I think the @sissy comment is spot on - I think it's an issue with your passing the object at different stages. And considering you're getting the error when you receive errors on Post.save, sissy will likely be correct

    Further, I'd imagine the fundamental problem would be this:

    @question ->
    
         !ruby/object:Question
          attributes:
             -- title: x
             -- created_at: y
             -- updated_at: z
    

    If you're parsing JSON, surely this would try to translate !ruby/object:Question into an array element, meaning it needs to be a String in order for it to work


    Fix

    I would fix it by changing the helper to this:

    #app/helpers/questions_helper.rb
    def show_random(post)
       returned_post = Post.random_question(post)
       returned_post.title
    end
    
    #app/models/post.rb
    Class Post < ActiveRecord::Base
        def self.random_question(post)
            joins(:question).where(#your conditions here)
        end
    end
    

    You could then use:

    <%= show_random(@post) %>
    
    0 讨论(0)
提交回复
热议问题