模型belongs_to两个模型创建动作

时间:2014-01-25 00:38:33

标签: ruby-on-rails nested-resources

我有三种模式:用户,问题和答案,如下:

Class Answer < ActiveRecord::Base
  belongs_to :user
  belongs_to :question
end

Class Question < ActiveRecord::Base
  belongs_to :user
  has_many :answers
end

Class User < ActiveRecord::Base
  has_many :questions
  has_many :answers
end

我的主要业务逻辑在于用户发布问题和其他用户回答问题的想法。我希望能够跟踪问题答案以及用户的答案,例如: @user.answers@question.answers

该视图包含问题内容和答案的形式。

我可以通过设计current_user帮助程序跟踪用户。

答案如何创建动作应如何?这对我来说有点混乱,对于我只会使用build的单一关联。

1 个答案:

答案 0 :(得分:2)

question.rb #enable nested_attributes

 accepts_nested_attributes_for :answers, :reject_if => proc { |o| o['content'].blank? } #assuming Answer has `content` field to hold the answer. Or replace with exact one.

的routes.rb

resources :questions do
  member do
    post :answer
  end
end 

问题控制器

def answer
  @question = Question.find(params[:id])
  @answer = @question.answers.build(params[:answer])
  @answer.user_id = current_user.id

  respond_to do |format|
    if @answer.save
      format.html { redirect_to @question, notice: 'Question was successfully updated.' }
      format.json { head :no_content }
    else
      format.html { render action: "show" } #assuming your comment form is here.
      format.json { render json: @answer.errors, status: :unprocessable_entity }
    end
  end
end

您的答案表格可能如下所示:

<%= form_for(:answer, url: answer_question_path(@question)) do |f| %>

  <%= f.text_field :content, :placeholder => "Your Answer" %> #You may modify your answer fields here.
  <%= f.submit 'Answer' %>

<% end %>