所以我正在建立一个论坛,除了查看回复之外,一切似乎都有效。当我去访问该页面时,它表示该方法未定义。由于我的回复是我的讨论节目动作,我知道以下几行是问题:
@posts = @discussion.posts
在我看来,我使用@ posts.reply但是失败了。我已经通过帖子检查了控制台并且user_id和discussion_id是正确的,所以我不确定是什么问题。如上所述,我认为我错误地使用上面的代码调用帖子?如果没有,那么请让我知道您希望看到的代码(如果有的话),我可以为您安排。
谢谢!
乔
#Post Model (Replies)
class Post < ActiveRecord::Base
belongs_to :discussion
belongs_to :user
end
#Discussion Model (Thread)
class Discussion < ActiveRecord::Base
belongs_to :user
has_many :posts
extend FriendlyId
friendly_id :subject, use: :slugged
end
#User Model
class User < ActiveRecord::Base
has_many :articles
has_many :discussions
has_many :posts, :through => :discussions
...
#Discussions Controller to SHOW Posts
class DiscussionsController < ApplicationController
...
def show
@discussion = Discussion.friendly.find(params[:id])
@users = User.all.order("created_at DESC")
@posts = @discussion.posts
render :layout => 'discussion'
end
...
end
#Posts Controller
class PostsController < ApplicationController
before_action :authenticate_user!
before_action :set_discussion, only: [:new, :create, :destroy]
def new
@post = @discussion.post.new
end
def create
# new does not insert the record into the database
@post = @discussion.posts.build(create_params)
@post.user = current_user
if @post.save
redirect_to @discussion, notice: "It has been posted!"
else
render :new # or redirect back
end
end
def destroy
@post = @discussion.posts.find(params[:id]).destroy
flash.notice = "Deleted"
redirect_to discussion_path(@discussion)
end
private
def create_params
# Only permit the params which the user should actually send!
params.require(:post).permit(:reply)
end
# Will raise an ActiveRecord::NotFoundError
# if the Discussion does not exist
def set_discussion
@discussion = Discussion.friendly.find(params[:discussion_id])
end
end
#View for showing Replies
<%= @posts.reply %>
Posted: <%= @posts.created_at.strftime("%b. %d %Y") %></p>
<p><%= link_to "Delete Comment", [@posts.discussion], data: {confirm: "Are you sure you wish to delete?"}, method: :delete %></p>
#View for Reply Form
<h2>Reply</h2>
<%= form_for [ @discussion, @posts ] do |f| %>
<p>
<%= f.label :reply, "Reply" %><br/>
<%= f.text_field :reply %>
</p>
<p>
<%= f.submit 'Submit' %>
</p>
<% end %>
错误:
undefined method `to_key' for #<ActiveRecord::Associations::CollectionProxy []>
(Highlighting the post form)
undefined local variable or method `posts' for #<#<Class:0x007fa71bd31228>:0x007fa721e5f018>
(Highlighting `<%= posts.reply %>`)
答案 0 :(得分:1)
此代码:
<%= @posts.reply %>
Posted: <%= @posts.created_at.strftime("%b. %d %Y") %></p>
<p><%= link_to "Delete Comment", [@posts.discussion], data: {confirm: "Are you sure you wish to delete?"}, method: :delete %></p>
应该是这样的:
<% @posts.each do |post| %>
Posted: <%= post.created_at.strftime("%b. %d %Y") %></p>
<p><%= link_to "Delete Comment", [post.discussion], data: {confirm: "Are you sure you wish to delete?"}, method: :delete %></p>
<% end %>
但是您的代码中存在更多错误,您需要修复它们。
希望这有帮助。