0

我有这个模型,如果我要创建一个帖子。我想自动保存用户 ID 和主题 ID。但它并没有发生,我知道它会自动存储 user_id 和 subject_id 。如果你能帮助我,有人可以解释我为什么更好。:)

    class Post
  include Mongoid::Document

  field :content, type: String

  belongs_to :subject, autosave: true
  belongs_to :user , autosave: true
  has_many :comments , dependent: :delete
  embeds_many :video_attachments , inverse_of: :post
  accepts_nested_attributes_for :video_attachments, autosave: true
  accepts_nested_attributes_for :comments, autosave: true
  accepts_nested_attributes_for :user, autosave: true

end

require "mongoid/token"
class Subject
  include Mongoid::Document
  include Mongoid::Token

  field :title , type: String
  field :desc , type: String
  field :instructor_id , type: String
  field :students , type: Array

  has_many :user
  has_many :post
  token length: 6

end

class User
  include Mongoid::Document

  field :id_number , type: String
  field :crypted_password , type: String
  field :salt , type: String
  field :fname , type: String
  field :lname , type: String
  field :mname , type: String

  #relations
  belongs_to :subject , polymorphic: true
  has_one :user_detail 
  has_many :posts
  has_many :comments
  accepts_nested_attributes_for :posts , autosave: true
  accepts_nested_attributes_for :user_detail , autosave: true

end
class PostsController < ApplicationController
  def create
    @post = Post.new(data)
    if @post.save
      redirect_to root_url 
    end
  end

  private
  def data
    params.require(:post).permit(:content, :posted_by , video_attachments_attributes: [:id , :video], user_attributes: [:id], subject_attributes: [:id])
  end

结尾

4

0 回答 0