Answerer的用户名不会显示在Rails中?

时间:2013-11-29 17:11:24

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

我是Rails 4的新手,我正在创建一个类似于Stack Overflow的Q& A网站。

我的问题页面与Stack Overflow上的问题页面非常相似。问题部分正在起作用,然后我得到了答案,这些答案也在起作用,但是,我希望能够在答案旁边找到回答者的名字。

我很确定我已正确设置控制器,模型和视图。我重置了数据库,但仍然出现错误。

这是我的代码:

#Answers_controller.rb create action
def create
    @answer = @question.answers.new(answer_params)
    @answer.user_id = current_user.username

    respond_to do |format|
      if @answer.save
        format.html { redirect_to [@question], notice: 'Answer was successfully created.' }
        format.json { render action: 'show', status: :created, location: @answer }
      else
        format.html { render action: 'new' }
        format.json { render json: @answer.errors, status: :unprocessable_entity }
      end
    end
  end

answer.rb(model):

class Answer < ActiveRecord::Base
  belongs_to :user
  belongs_to :question


  validates :body, presence: true
end

#Then in user.rb I have has_many :answers, has_many :questions
#Also in question.rb has_many :answers

答案/ _answer.html.erb:

    <%= answer.username %>
    <%= answer.body %>
  </p>
  <p>
    <% if current_user.present? && current_user == answer.user %>
        <%= link_to 'Delete Answer', [answer.question, answer],
               method: :delete,
               data: { confirm: 'Are you sure?' } %>
    <% end %>
  </p>

然后在问题/节目中:

<div class="container">
    <div class="row">
    <div class="span8">
        <h3><%= @question.title %>
      <% if current_user.present? && current_user == @question.user  %>
        <%= link_to 'Edit', edit_question_path(@question) %></h3>
      <% end %>
      <hr>
    </div>
  </div>
  <div class="row">
    <div class="span8">
      <p><%= @question.description %></p>
        Asked by <%= @question.user.full_name %>
      <hr>
    </div>
    </div>

  <%= render "answers/form" %>
  <%= render @question.answers %>
</div>

<script type="text/javascript">
  $(document).ready(function(){

    $('.wysihtml5').each(function(i, elem) {
      $(elem).wysihtml5();
    });

  })
</script>  

2 个答案:

答案 0 :(得分:0)

这看起来你错了

@answer = @question.answers.new(answer_params)

尝试

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

说明:您构建了一个新的answer,但未将其引用到question,因为has_many documentation根据collection.build(attributes = {}, …)而不是collection.new(attributes)

答案 1 :(得分:0)

有一些突出的事情:

#Answers_controller.rb create action
def create
   @answer = @question.answers.new(answer_params)
   @answer.user_id = current_user.username # ???? should be current_user.id   ????
   # omitted
end

答案/ _answer.html.erb

<%= answer.username %> # ???? you have no username field on your answer model ???
# ??? should be <%= answer.user.username %> ???
<%= answer.body %>
</p>

  # omitted