我有三种模式:用户,问题和答案,如下:
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
的单一关联。
答案 0 :(得分:2)
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.
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 %>