2017-01-27 3 views
0

Все, что я должен упомянуть, что я впервые в Rails разрабатываю и пытаюсь учиться, когда я иду. Я использовал направление из этого блога для создания публикации и комментариев. Я немного изменил его, чтобы иметь отношения. Но я пытаюсь связать комментарий с сообщением, и я не получаю этих результатов. Я отправляю, но это не под конкретного поста .... пожалуйста, помогитеКак связать мои комментарии к сообщению в Rails

Что я пытаюсь сделать:

  1. Разрешить пользователю создать кампанию (по существу, название и описание)
  2. Разрешить пользователю иметь много Кампании
  3. Позвольте пользователю иметь сторонника кампании (у меня есть код для этого)
  4. Позвольте пользователю прокомментировать кампанию .... Поэтому, по сути, пользователь должен войти в систему, кампанию, а затем можете прокомментировать кампанию

маршрутов ПУЭ:

Rails.application.routes.draw do 

resources :commentonsqueals 
resources :squeals 
devise_for :users 
resources :users do 
get "users/show_image" => "users#show_image" 
member do 
    get :following, :followers 
end 

конца

контроллер Пользователей: Завещания: database_authenticatable,: регистрируемые, : возмещены,: запоминающийся,: отслеживается,: подтверждаемые has_attached_file: аватара: стили => {: medium => "300x300>",: thumb => "100x100 #"},: default_url => "/images/:style/missing.png" validates_attachment_content_type: avatar,: content_type =>/\ Aimage/. * \ Z/

 has_many :comments 

    has_many :Squealingcampaign,dependent: :destroy # 
    has_many :campaign,dependent: :destroy # 
    has_many :followeds, through: :relationships 
     has_many :relationships, foreign_key: "follower_id", dependent: :destroy 
    has_many :followed_users, through: :relationships, source: :followed 
    has_many :reverse_relationships, foreign_key: "followed_id" 
    has_many :reverse_relationships, foreign_key: "followed_id", 
           class_name: "Relationship", 
           dependent: :destroy 
    has_many :followers, through: :reverse_relationships, source: :follower 


    has_many:avatar, dependent: :destroy 
    has_many :posts, dependent: :destroy # remove a user's posts if his account is deleted. 
    has_many :active_relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy 
    has_many :passive_relationships, class_name: "Relationship", foreign_key: "followed_id", dependent: :destroy 

    has_many :following, through: :active_relationships, source: :followed 
    has_many :followers, through: :passive_relationships, source: :follower 

КОММЕНТАРИИ ПО визгом CONTROLLER

class CommentonsquealsController < ApplicationController 
before_action :set_commentonsqueal, only: [:show, :edit, :update, :destroy] 

# GET/commentonsqueals # GET /commentonsqueals.json Защиту индекс @commentonsqueals = Commentonsqueal.all конец

# GET/commentonsqueals/1 # GET /commentonsqueals/1.json def show конец

# GET/commentonsqueals/новый Защиту нового @commentonsqueal = Commentonsqueal.new

конца

# GET/commentonsqueals/1/редактировать Защиты редактировать конечных

# POST/commentonsqueals # POST /commentonsqueals.json def create @commentonsqueal = Commentonsqueal.new (commentonsqueal_params)

respond_to do |format| 
if @commentonsqueal.save 
    format.html { redirect_to @commentonsqueal, notice: 'Commentonsqueal was  successfully created.' } 
    format.json { render :show, status: :created, location: @commentonsqueal } 
    else 
    format.html { render :new } 
    format.json { render json: @commentonsqueal.errors, status: : :unprocessable_entity } 
    end 
end 

конец

# PATCH/PUT/commentonsqueals/1 # PATCH/PUT /commentonsqueals/1.json Защиту обновить respond_to сделать | формат | если @ commentonsqueal.update (commentonsqueal_params) формат.html {redirect_to @commentonsqueal, обратите внимание: «Commentonsqueal был успешно обновлен». } format.json {визуализации: шоу, статус:: хорошо, местоположение: @commentonsqueal} еще format.html {визуализации: редактировать} format.json {визуализации JSON: @ commentonsqueal.errors статус:: unprocessable_entity} конец конец конец

# УДАЛИТЬ/commentonsqueals/1 # УДАЛИТЬ /commentonsqueals/1.json защиту уничтожить @ commentonsqueal.destroy respond_to делать | формат | format.html {redirect_to commentonsqueals_url, обратите внимание: 'Commentonsqueal был успешно уничтожен.' } format.json {голова: no_content} конец конец

частный # Используйте обратные вызовы имеют общие настройки или ограничения между действиями. Защиту set_commentonsqueal @commentonsqueal = Commentonsqueal.find (Params [: ID]) конец

# Never trust parameters from the scary internet, only allow the white list through. 
def commentonsqueal_params 
    params.require(:commentonsqueal).permit(:squeal_id, :body) 
end 

конец

КОММЕНТАРИИ визжать МОДЕЛЬ

class Commentonsqueal < ActiveRecord::Base 
belongs_to :post 
end 

<tbody> 
<% @commentonsqueals.each do |commentonsqueal| %> 
<tr> 
<td><%= commentonsqueal.squeal_id %></td> 
<td><%= commentonsqueal.body %></td> 
<td><%= link_to 'Show', commentonsqueal %></td> 
<td><%= link_to 'Edit', edit_commentonsqueal_path(commentonsqueal) %></td> 
<td><%= link_to 'Destroy', commentonsqueal, method: :delete, data: { confirm: 'Are you sure?' } %></td> 
    </tr> 
<% end %> 

<%= link_to 'New Commentonsqueal', new_commentonsqueal_path %> 

Когда я пытаюсь добавить комментарии это как раз не присоединять или быть под постом, что я сделал

ответ

0

я нашел свое решение для отображения поста, связанный друг с другим

def show 
@comments = Commentonsqueal.all.where("squeal_id = ?",  Squeal.find_by_id(params[:id])) 
end 
Смежные вопросы