Rails 4 form - no implicit conversion of Model into String

前端 未结 2 1536

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: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) %>
    

提交回复
热议问题