dimanche 21 février 2016

Create multiple relationships

I am developing a Q&A app and the thing is, I want to add the ability for people to post answers.

I already built a migration so that the question has the same id of the user with rails g migration add_user_id_to_questions and then added the has_many/belongs_to

Now I am stuck with how to create a relationship for the answers.

I already added a answer scaffold with: rails g scaffold Answer answer:integer

And then I did a migration: (Was it a right move? to create a migration so that answers have the same ID as the question?)

rails g migration add_answer_id_to_answers

And added the has_many/belong_to as well.

But now what? How do I make answer the to have the same ID of the question? Because inside the show view, if a user posts an answer it will basically be visible on every question...

Show view:

      <% @answers.each do |answer| %>

      <div class="well bgBlack">
          <div class="media">
            <a class="pull-left">
            <% if answer.user.avatar.blank? %>
                <img src="http://ift.tt/2176wHd" style="width: 75px;">
            <% elsif answer.user.avatar %>
                <%= image_tag answer.user.avatar, :style => "width:75px;" %>
            <% end %>
            </a>
            <div class="media-body">
              <p class="white"><%= link_to answer.user.username, answer.user, :class => " bg" %></p>
              <p class="white small"><%= answer.answer %></p>
           </div>
           <div class="pull-right">
                <% if user_signed_in? %>
                    <% if answer.user_id == current_user.id %>
                        <%= link_to 'delete', answer_path(answer), :method => :delete, :class => "text-muted white" %>
                    <% end %>
                <% end %>
           </div>
        </div>
      </div>                

      <% end %>

User model:

class User < ActiveRecord::Base
  mount_uploader :avatar, AvatarUploader
  has_many :questions, :dependent => :destroy
  has_many :answers, :dependent => :destroy

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

Question model:

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

Answer model:

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

Answer controller:

class AnswersController < ApplicationController
  before_action :set_answer, only: [:destroy]

  respond_to :html

  def create
    @answer = current_user.answers.build(answer_params)
    @answer.save
    redirect_to :back
  end

  def destroy
    @answer.destroy
    redirect_to :back
  end

  private
    def set_answer
      @answer = Answer.find(params[:id])
    end

    def answer_params
      params.require(:answer).permit(:answer)
    end
end

Aucun commentaire:

Enregistrer un commentaire