以用户身份创建帖子并将其分配给组

时间:2014-12-23 12:08:58

标签: ruby-on-rails post ruby-on-rails-4 relationship

在我的rails应用程序中,我制作了三个模型,User,Group和Post。 我试图让@ post.group等于@ group.id 帖子是从#show controller组内的渲染中发布的,然后将自身重定向到post #create controller。如何将@ post.group设置为@ group.id?

GroupsController

class GroupsController < ApplicationController
  before_action :set_group, only: [:show, :edit, :update, :destroy]

  respond_to :html

  def index
    @groups = Group.all
    respond_with(@groups)
  end

  def show
    @group_id = @group.id
    respond_with(@group)
  end

  def new
    @group = Group.new
    respond_with(@group)
  end

  def edit
  end

  def create
    @group = Group.new(group_params)
    @group.save
    respond_with(@group)
  end

  def update
    @group.update(group_params)
    respond_with(@group)
  end

  def destroy
    @group.destroy
    respond_with(@group)
  end

  private
    def set_group
      @group = Group.find(params[:id])
    end

    def group_params
      params.require(:group).permit(:name, :description, :motto, :usercount, :group, :id, :groupid)
    end
end

PostsController

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]

  respond_to :html

  def index
    @posts = Post.all
    respond_with(@posts)
  end

  def show
    respond_with(@post)
  end

  def new
    @post = Post.new
    respond_with(@post)
  end

  def edit
  end

  def create
    @post.group = @group_id
    @post = Post.new(post_params)
    @post.save
    respond_with(@post)
  end

  def update
    @post.update(post_params)
    respond_with(@post)
  end

  def destroy
    @post.destroy
    respond_with(@post)
  end

  private
    def set_post
      @post = Post.find(params[:id])
    end

    def set_group
      @group = Group.find(params[:id])
    end

    def post_params
      params.require(:post).permit(:body, :group, :id)
    end

    def group_params
      params.require(:group).permit(:id, :groupid, :group)
    end
end

PostModel

class Post < ActiveRecord::Base
  belongs_to :group
end

GroupsModel

class Group < ActiveRecord::Base
  has_many :posts
end

我当前的代码返回错误undefined method group =&#39;为零:NilClass` 任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

您应该从创建Post实例开始,因为您不会这样做。我会这样做:

def create
  @post = @group.posts.build(post_params)
  if @post.save
    # handle success
  else
    # handle error
  end
end

还有什么,您应该在before_action :set_group中设置PostsController