【问题标题】:How to convert an array from psql databse into a list of strings?如何将mysql数据库中的数组转换为字符串列表?
【发布时间】:2015-06-06 14:33:45
【问题描述】:

我正在为一个最终项目构建一个测验应用程序,它将于下周到期。我一直在努力解决一个试图将数组转换为字符串列表的问题。

问卷模型:

class Questionnaire < ActiveRecord::Base

  belongs_to :categories

end

Chose_answer.html.erb

<h1>Congrats You Hit The Choices Page!</h1>

<%= semantic_form_for @questions.choices do |c| %>

  <%= c.inputs do %>

    <%= c.input :choices, :as => :check_boxes , :collection => 
   [@questions.choices].map(&:inspect).join(', ') %>

  <% end %>

<% end %>

问卷调查员:

class QuestionnairesController < ApplicationController

  def index

    @questions = Questionnaire.find(params[:category_id])
    #params[:category_id]= <%=category.id%>
    @category = Category.find(params[:category_id])
    @videos = VideoClue.find(params[:category_id])
    ###This finds all the questions from the question table by their category_id. Whenever I select a category, it matches the question related to the category

    render :show
    ###render :show Renders Html page
  end

  def choose_answer
    # binding.pry
    @questions = Questionnaire.find(params[:id])
    #params[:id] = /:id  = /1


    render :choose_answer
  end

问卷表种子:

Questionnaire.create({question: "In that year did MTV (Music Television) 

premiere and what was the first music video the channel aired?", choices:

["1982 Michael Jackson 'Bille Jean'", "1984 Madonna 'Like a virgn'", "1981

The Buggles 'Video Killed The Radio Star'"], correct_answer:"1981 The 

Buggles 'Video Killed The Radio Star' ", category_id:1})

@question.choices 返回

["1982 Michael Jackson 'Bille Jean'", "1984   

Madonna 'Like a virgin'", "1981 The Buggles 'Video Killed The Radio Star'"], 

我想将“选择”转换为列表。我想用formtastic把它们变成多项选择我应该怎么做?请我需要有人帮助回答这个问题,因为我真的很想按时完成我的项目并让它工作。

【问题讨论】:

  • 您的关联应该是belongs_to :category
  • 我的数据库表名叫做categories。为什么要分类?
  • belongs_to 关联应该始终是单数而不是复数
  • 您在实际代码中在哪里使用@question.choices?另外,当您@questions = Questionnaire.find(params[:category_id]) 时,您是否正在寻找属于特定类别的问卷(不是问题)? @questions 是否返回任何内容?

标签: ruby-on-rails ruby psql formtastic


【解决方案1】:

查看文档here。您可以将数组作为集合传递:

&lt;%= c.input :choices, :as =&gt; :check_boxes , :collection =&gt; @questions.choices %&gt;

【讨论】:

  • @question.choices 返回的是什么?您可以查看样本数据&lt;%= c.input :choices, :as =&gt; :check_boxes , :collection =&gt; ["1982 Michael Jackson 'Bille Jean'", "1984 Madonna 'Like a virgin'", "1981 The Buggles 'Video Killed The Radio Star'"] %&gt;
  • 它返回数组本身。
  • 当我执行 [@questions.choices] 时,它返回 |check box| [“1982 年迈克尔·杰克逊 'Bille Jean'”、“1984 年麦当娜 '像处女'”、“1981 年 The Buggles '视频杀死了广播明星'”]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多