【发布时间】:2017-04-27 13:23:46
【问题描述】:
在我的应用程序中,我有模型 Post & Slides & 我有:
class Post < ActiveRecord::Base
has_many :slides, inverse_of: :post
accepts_nested_attributes_for :slides, reject_if: :all_blank, allow_destroy: true
一切正常,只有我需要(因为我的应用程序将如何工作),当创建 slide 时,我需要将其分配 current_user 或正在创建记录的用户。
我的slides 表中已经有user_id 并且:
class User < ActiveRecord::Base
has_many :posts
has_many :slide
end
class Slide < ActiveRecord::Base
belongs_to :user
belongs_to :post
end
我的PostsController 看起来像这样:
def new
@post = current_user.posts.build
// This is for adding a slide without user needing to click on link_to_add_association when they enter new page/action
@post.slides.build
end
def create
@post = current_user.posts.build(post_params)
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Was successfully created.' }
else
format.html { render :new }
end
end
end
感谢任何帮助!
【问题讨论】:
标签: ruby-on-rails-4 nested-attributes assign cocoon-gem