Rails 4表单 – 没有将Model隐式转换为String

添加帮助器方法并编辑我的表单后,我收到此错误

TypeError in Posts#create Showing /Users/jim/project/test/app/views/posts/_form.html.erb where line #2 raised: no implicit conversion of Question into String Extracted source (around line #2): 1 2  3 app/helpers/questions_helper.rb:4:in `show_random' app/views/posts/_form.html.erb:2:in `_app_views_posts__form_html_erb___4147312638633006209_2202637820' app/views/posts/new.html.erb:3:in `_app_views_posts_new_html_erb___3518261482060642021_2203102520' app/controllers/posts_controller.rb:33:in `create' Request Parameters: {"utf8"=>"✓", "authenticity_token"=>"MK1wiBKc8MqXsKPtvbgJWaBNAaZ7kHm7RDVC8ZYRMNc=", "post"=>{"question_id"=>"1", "content"=>""}, "commit"=>"Create Post"} 

但是,如果满足Post模型的validation,则不会出现此错误。 所以我猜测(不确定)我的Posts controller create操作中的if else statement有问题,但我不知道如何修复它。

questions_helper.rb

 module QuestionsHelper def show_random(random) JSON.parse(random).with_indifferent_access end end 

_form.html.erb

    
show_random(@question)[:id] %>

posts_controller.erb

  def new @post = Post.new @question = cookies[:question] ||= Question.random # the random method return a random question serialized record using to_json end def create @post = current_user.posts.build(post_params) if @post.save flash[:success] = "Post created successfully!" else @question = Question.where(id: params[:post][:question_id]).first render 'new' end 

我发现问题归功于@sissy评论。

我应该传递@question = cookies[:question]而不是@question = Question.where(id: params[:post][:question_id]).first在我的posts controller create动作中

谢谢大家的帮助。

你的助手似乎对我很怀疑 – 你传递一个Ruby对象并尝试将其解析为JSON

我认为@sissy的评论很明显 – 我认为这是你在不同阶段传递对象的问题。 考虑到你在Post.save上收到错误时收到错误,娘娘腔可能是正确的

此外,我认为根本问题是:

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

如果你正在解析JSON,肯定会尝试翻译!ruby/object:Question到一个数组元素,这意味着它需要是一个String才能使它工作


固定

我会通过更改帮助器来解决此问题:

 #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 

然后你可以使用:

 <%= show_random(@post) %>