我有一个Post模型和Summary模型,其中一个帖子只有一个模型。
#Post Model
class Post < ActiveRecord::Base
has_one :summary, dependent: :destroy
default_scope { order('rank DESC') }
scope :visible_to, -> (user) { user ? all : joins(:topic).where('topics.public' => true ) }
validates :title, length: {minimum: 5}, presence: true
validates :body, length: {minimum: 20}, presence: true
validates :topic, presence: true
validates :user, presence: true
#Summary Model
class Summary < ActiveRecord::Base
belongs_to :post
validates :body, length: { maximum: 100 }, presence: true
end
当我尝试使用摘要创建帖子时,通过单击“保存”按钮是标准表单,我视图中的某些内容会导致错误。
undefined method `summary' for #<Post::ActiveRecord_Associations_CollectionProxy:0x007ff7fdcafd80>
<div class="row"> <!-- what others are there besides row? -->
<div class="col-md-12">
<div class="pull-right">
<h1><%= markdown @post.title %></h1>
<h4><%= markdown @post.summary.body %></h4> ** Its the summary in this line **
<%= render partial: 'votes/voter', locals: { post: @post } %>
<p><%= markdown @post.body %></p>
<p><%= image_tag @post.image.url(:thumb) if @post.image? %></p>
</div>
</div>
显然,我无法在帖子上发送摘要。 因为summary是它自己的类,所以我在上面的视图和相应的控制器中遇到了变量。
class Topics::PostsController < ApplicationController
def create
@topic = Topic.find(params[:topic_id])
@post = current_user.posts.build(post_params)
@post.topic = @topic
@summary = @post.build(summary_params)
@summary = @post.summary
authorize @post
if @post.save && @summary.save
@post.create_vote
flash[:notice] = "Post was saved."
redirect_to [@topic, @post]
else
flash[:error] = "There was an error saving the post. Please try again."
render :new
end
end
我的名字是否混淆了?我应该如何加入这两个模型来创建和显示新帖子的摘要?
答案 0 :(得分:2)
请改为尝试:
def create
@topic = Topic.find(params[:topic_id])
@post = current_user.posts.build(post_params)
@post.topic = @topic
authorize @post
if @post.save
@summary = @post.build_summary(summary_params)
if @summary.save
@post.create_vote
flash[:notice] = "Post was saved."
redirect_to [@topic, @post]
end
else
flash[:error] = "There was an error saving the post. Please try again."
render :new
end
end