2015-04-28 1 views
1

У меня есть модель публикации и модель комментария, которая принадлежит Post. Я смог отобразить сообщение в домашнем виде, соответствующее домашнему контроллеру и домашнему действию, а также представление User/show. Таким образом, в домашних и пользовательских представлениях записи перечисляются в порядке времени создания. Я также мог иметь форму сообщения как в представлении пользователя, так и дома.Как создать форму комментариев и правильно работать на моей домашней странице?

Проблема возникает, когда я пытаюсь отобразить форму комментариев под каждым отображаемым сообщением в представлении дома и пользователя. Домашний контроллер/домашнее действие уже имеет переменную @post для новой отображаемой формы сообщения, что затрудняет инициализацию другой переменной экземпляра post для создаваемого комментария. Форма комментария должна находиться под соответствующей статьей, что приведет к созданию комментария к этой статье.

Как реализовать это в домашнем виде? Как инициировать переменные Post и comment, необходимые для обработки формы комментариев?

Вот мой дом вид: приложение/просмотров/дом/home.html.erb:

<% if logged_in? %> 
<div class="row"> 
<aside class="col-md-4"> 
    <section class="user_info"> 
    <%= render 'shared/user_info' %> 
    </section> 
    <hr/> 
    <br/> 
    <section class="stats"> 
    <%= render 'shared/stats' %> 
    </section> 
    <section class="post_form"> 
<%= render 'shared/post_form' %> 
</section> 
</aside> 
<div class="col-md-8"> 
<h3>Post Feed</h3> 
<%= render 'shared/feed' %> 
</div> 
</div> 
<% else %> 
<div class="center jumbotron"> 
<h1>Welcome to the Unstarv website</h1> 
<h2> 
Please sign up now to use this site 
<%= link_to "Sign Up", signup_path =%> 
now. 
</h2> 
<%= link_to "Sign up now!", signup_path, class: "btn btn-lg btn-primary" %> 
</div> 
<%= link_to image_tag("rails.png", alt: "unstarv logo"), 
     '#' %> 
     <% end %> 

А вот мой домашний контроллер:

class HomeController < ApplicationController 
def home 
    if logged_in? 
@post = current_user.posts.build 
@feed_items = current_user.feed.paginate(page: params[:page]) 
end 
end 
def about 
end 
def privacy 
end 
def terms 
end 
end 

А вот мой пост модель, соответствующая часть:

class Post < ActiveRecord::Base 
belongs_to :user 
has_many :comments 
default_scope -> { order(created_at: :desc) } 
mount_uploader :picture, PictureUploader 
end 

соответствующая часть моей модели пользователя:

class User < ActiveRecord::Base 
attr_accessor :remember_token 
before_save { self.email = email.downcase } 
has_many :posts, dependent: :destroy 
has_many :comments 
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 
validates :username, presence: true, length: { maximum: 50 } 
VALID_EMAIL_REGEX = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i 
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, 
       uniqueness: { case_sensitive: false } 
       has_secure_password 
       validates :password, length: { minimum: 6 }, allow_blank: true 



def feed 
following_ids = "SELECT followed_id FROM relationships 
       WHERE follower_id = :user_id" 
Post.where("user_id IN (#{following_ids}) 
       OR user_id = :user_id", user_id: id) 
end 
end 

А вот мой комментарий модель:

class Comment < ActiveRecord::Base 
belongs_to :post 
belongs_to :user 
default_scope -> { order(created_at: :desc) } 
end 

А вот пост управления:

class PostsController < ApplicationController 
before_action :logged_in_user, only: [:create, :destroy] 
def index 
@posts = Post.all 
end 
def show 
    @post = Post.find(params[:id]) 
    @comment = Comment.new 
    @comment.post_id = @post.id 
    @comments = @post.comments.all 
end 
def new 
    @post = Post.new 
end 
def create 
@post = current_user.posts.build(post_params) 
if @post.save 
    flash[:success] = "Post created!" 
    redirect_to root_url 
else 
    @feed_items = [] 
    render 'home/home' 
end 
end 
def edit 
@post = Post.find(params[:id]) 
end 
    def update 
@post = Post.find(params[:id]) 
@post.update(post_params) 
flash.notice = "Post '#{@post.title}' Updated!" 
render 'home/home ' 
end 

def update 
@post = Post.find(params[:id]) 
@post.update(post_params) 
flash.notice = "Post '#{@post.title}' Updated!" 
redirect_to root_url 
end 

private 
# Use callbacks to share common setup or constraints between actions. 
def set_post 
    @post = Post.find(params[:id]) 
end 

# Never trust parameters from the scary internet, only allow the white list through. 
def post_params 
    params.require(:post).permit(:title, :body, :picture) 
end 
end 

Вот мое приложение/просмотров/запись/_post.html.erb файл,

<li id="post-<%= post.id %>"> 
<span class="user"><%= link_to post.user.username, post.user %></span> 
<span class="content"> 
<%= post.title %> 
<%= post.body %> 
<%= image_tag post.picture.url if post.picture? %> 
</span> 
<span class="timestamp"> 
Posted <%= time_ago_in_words(post.created_at) %> ago. 
<% if current_user?(post.user) %> 
    <%= link_to "delete", post, method: :delete, 
            data: { confirm: "You sure?" } %> 
<% end %> 
</span> 
<section> 
<h2>Your Comments here</h2> 
<h3>Post a Comment</h3> 
<h3>Post a Comment</h3> 
<%= render 'shared/comment_form' %> 
<% post.comments.all.each do |comment| %> 
<h4><small>Comment by</small> <%= comment.post.user.username %></h4> 
<p class="comment"><%= comment.body %></p> 
<p><small>Posted <%= distance_of_time_in_words(Time.now,  comment.created_at) %> ago</small></p> 
<br/> 
<%end%> 
</li> 

А вот мое приложение/просмотров/общий/comment_form_html.erb, который, кажется, часть проблемы, как т он переменные экземпляра не правильно инициализированы:

<%= form_for [ @post1, @comment] do |f| %> 
<p> 
<%= f.label :body, "Your Comment" %><br/> 
<%= f.text_area :body %> 
</p> 
<p> 
<%= f.submit 'Submit' . method="post", class: 'btn btn-primary' %> 
</p> 
<% end %> 

И, наконец, вот мой след:

actionview (4.1.8) lib/action_view/helpers/form_helper.rb:423:in `form_for' 
app/views/shared/_comment_form.html.erb:1:in  `_app_views_shared__comment_form_html_erb__972919349_34226064' 
actionview (4.1.8) lib/action_view/template.rb:145:in `block in render' 
activesupport (4.1.8) lib/active_support/notifications.rb:161:in `instrument' 
actionview (4.1.8) lib/action_view/template.rb:339:in `instrument' 
actionview (4.1.8) lib/action_view/template.rb:143:in `render' 
actionview (4.1.8) lib/action_view/renderer/partial_renderer.rb:306:in `render_partial' 
actionview (4.1.8) lib/action_view/renderer/partial_renderer.rb:279:in `block in render' 
actionview (4.1.8) lib/action_view/renderer/abstract_renderer.rb:38:in `block in instrument' 
activesupport (4.1.8) lib/active_support/notifications.rb:159:in `block in instrument' 
activesupport (4.1.8)lib/active_support/notifications/instrumenter.rb:20:in `instrument' 
activesupport (4.1.8) lib/active_support/notifications.rb:159:in `instrument' 
actionview (4.1.8) lib/action_view/renderer/abstract_renderer.rb:38:in `instrument' 
actionview (4.1.8) lib/action_view/renderer/partial_renderer.rb:278:in `render' 
actionview (4.1.8) lib/action_view/renderer/renderer.rb:47:in `render_partial' 
actionview (4.1.8) lib/action_view/helpers/rendering_helper.rb:35:in `render' 
app/views/posts/_post.html.erb:22:in `_app_views_posts__post_html_erb__365860364_28803540' 
actionview (4.1.8) lib/action_view/template.rb:145:in `block in render' 
activesupport (4.1.8) lib/active_support/notifications.rb:161:in `instrument' 
actionview (4.1.8) lib/action_view/template.rb:339:in `instrument' 
actionview (4.1.8) lib/action_view/template.rb:143:in `render' 
actionview (4.1.8) lib/action_view/renderer/partial_renderer.rb:399:in `block in collection_with_template' 
actionview (4.1.8) lib/action_view/renderer/partial_renderer.rb:395:in `map' 

Большое спасибо за вашу помощь !!!!

ответ

1

в _post.html.erb, изменить <%= render 'shared/comment_form' %> с render 'shared/comment_form', post: post

, а затем в _comment_form_html.erb, изменить [@post1, @comment] с [post, @comment]

EDIT

Кроме того, необходимо добавить следующую строку в HomeController#home

@comment = Comment.new 

EDIT

Вопрос/Вопрос заключается в том, как вы можете создать экземпляр, который будет использоваться в каждой форме комментариев, верно?

Поскольку вы перебор каждого пост <%= render 'shared/feed' %>, у вас уже есть поста экземпляр, вы обращаетесь к этому экземпляру в app/views/post/_post.html.erb, имя экземпляра post.

При попытке оказать comment_form, вы можете передать параметры метода render, вы можете отправить параметр называется locals или просто отправить paremeter, как name=value что является shorcut.

Если вы предоставите comment_form, отправив текущее post, вы можете сгенерировать форму, основанную на этом сообщении.

так как теперь у вас есть доступ к post в shared/_comment_form.html.erb, текущий вопрос, как генерировать comment экземпляр, один путь к экземпляру комментарий в каждом действии контроллера, где вы хотите, чтобы показать канал (плохой вариант, если он используется в несколько мест) и это то, что я сказал в комментарии (мой плохой). Я думаю, что лучшим вариантом является изменение [@post1, @comment] (ваше исходное решение) с [post, post.comments.build]

Как это работает? Поскольку у вас уже есть доступ к post, вы можете просто создать пустой комментарий для этого post на вид

+0

Как правило, ответы гораздо полезнее, если они содержат объяснение того, что должен делать код, и почему это решает проблему проблема без введения других :) –

+0

Aguardientico, он все еще не работает. Я получаю ArgumentError в доме # домой. По-видимому, я получаю ошибку, что первый аргумент в форме не может содержать nil или быть пустым, что в этом случае является аргументом post в форме. – codigomonstruo

+0

Вы правы @ JaimeGómez Я попытаюсь обновить ответ позже. – Aguardientico