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

时间:2014-03-10 10:22:56

标签: ruby-on-rails ruby-on-rails-4

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

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      <%= show_random(@question)[:title] %>
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模型的验证,则不会出现此错误。所以我猜测(不确定)if else statementcreate我的Posts controller行动中出现了问题,但我不知道如何修复它。

questions_helper.rb

module QuestionsHelper

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

end

_form.html.erb

<%= show_random(@question)[:title] %>

<%= form_for(@post) do |f| %>

  <%= render 'shared/error_messages', object: f.object %>

  <div>
    <%= f.hidden_field :question_id, :value => show_random(@question)[:id] %><br>
  </div> 

  <div>
    <%= f.label :content %><br>
    <%= f.text_area :content %>
  </div>

  <div>
    <%= f.submit %>
  </div>
<% end %>

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

2 个答案:

答案 0 :(得分:2)

感谢@sissy评论,我发现了这个问题。

我应该在@question = cookies[:question]

@question = Question.where(id: params[:post][:question_id]).first行动中通过create代替posts controller

感谢大家的帮助。

答案 1 :(得分:0)

你的助手似乎对我很怀疑 - 你传递一个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) %>