【问题标题】:How to store an ID to answers如何将 ID 存储到答案
【发布时间】:2016-02-22 12:36:47
【问题描述】:

我有一个问答应用程序,用户可以在其中提出问题并获得答案。我在回答部分遇到了一些问题。

我正在尝试将问题的 ID 存储在答案表中,但是当我在控制台中检查它时它总是返回 nil。

  def new
    #question scaffold
    if user_signed_in? 
      @question = current_user.questions.build
      respond_with(@question)
    else
      redirect_to new_user_session_path
    end
    #answer scafold
      @answer = Answer.create
      @question = Question.find(params[:id])
      @answer.question_id = @question
      @answer.save!
      redirect_to root_path
  end

  def edit
  end

  def create
    #create question
    @question = current_user.questions.build(question_params)
    @question.save

    #create answer
    @answer = Answer.create(answer_params)
    @question = Question.find(params[:id])
    @answer.question_id = @question
    @answer.save!
    redirect_to :back
  end

【问题讨论】:

  • 你和问答表有什么关联
  • 答案表可以看作是 cmets,如果它更容易的话。我已经建立了与 has_many 和 belongs_to 的关系。当我在控制台中手动添加question_id 时,它运行良好并在正确的问题中显示答案。我想要做的是将问题的 ID 存储在答案表中,而无需实际进入控制台并自己做

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


【解决方案1】:

您的代码有几个问题。首先,您应该添加一个数据库约束,以防止在没有问题 ID 的情况下保存答案。生成执行此操作的迁移。

add_foreign_key :answers, :questions

使用验证确保答案需要设置question_id

class Answer < ActiveRecord::Base
  validates :question_id, presence: true
end

您还应该使用 ActiveRecord 关系来更轻松地构建模型。

@answer = @question.answers.build(answer_params)
@answer.save

这给我们带来了您的代码问题。我不清楚new 在这里做什么。是两个动作吗?一个动作?如果这是一项操作,则您将 @answer.question_id 设置为空白值,因为 @question 已构建,并且未保存。

另外,请确保您使用的是strong_parameters 和白名单属性,用户可以在表单中设置。

【讨论】:

  • 我刚刚注意到我们俩实际上住在同一个国家。您是否开放私人会议或任何会议?
  • @Raymond 能帮我个忙吗?您能否更新问题中的代码以显示每个控制器以及该控制器中的相关操作?我是黎巴嫩人,但这些天我住在巴西的圣保罗。但我很乐意尽我所能提供帮助。
  • 有没有办法给你私信?
【解决方案2】:

您刚刚在操作中创建了问题,为什么您希望将问题 ID 发送到操作,请检查以下我更改了#create answer 部分以使用创建的问题:(我错过了什么吗?)

def create
 #create question
 @question = current_user.questions.build(question_params)
 @question.save

 #create answer
 @answer = Answer.create(answer_params)
 @answer.question = @question
 @answer.save!
 redirect_to :back
end

【讨论】:

    猜你喜欢
    • 2012-12-23
    • 2019-01-24
    • 2012-10-01
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 2020-01-01
    • 2013-06-03
    相关资源
    最近更新 更多