【问题标题】:Form field user can't be blank in rails (user not getting associated with form submission/model)表单字段用户在 Rails 中不能为空(用户未与表单提交/模型关联)
【发布时间】:2013-09-06 21:13:59
【问题描述】:

我有两个模型。一个集合和一个设计。

收藏有_许多设计和设计属于_一个收藏。

除了一件事,一切都很好。用户将创建一个集合,该集合使用 current_user 与他们的 user_id 关联,就像在我的 Collection 控制器中一样

def create
  @collection = current_user.collections.build(collection_params)
end

这很好用,并且 user_id 将与之相关联。不幸的是,我的问题是在集合中创建设计。因此,用户创建了一个集合,然后转到该集合页面。如果用户创建了该集合,则会出现一个显示添加设计的按钮。出现添加设计表单,您可以提交设计,但没有 user_id 与创建的设计相关联,尽管设计确实与集合相关联。

这是我的设计控制器

def create
  @collection = current_user.collections.find(params[:collection_id])
  @design = @collection.designs.build(design_params)
end

我有这些私有的 before_actions

def set_design
  @collection = Collection.find(params[:collection_id])
  @design = @collection.designs.find(params[:id])
end

def find_collection
  @collection = Collection.find(params[:collection_id])
end

有人知道我做错了什么吗?让我知道您是否需要查看类似这些模型的其他内容...

提前谢谢伙计们/姑娘们……祝你好运

【问题讨论】:

  • 用户和设计之间是什么关系?如果它是一个“多次通过”的集合,那么您就不需要根据您展示的内容将 user_id 直接与设计相关联。
  • 是的,这是我的用户模型:has_many :designs, :through => :collections, dependent: :destroyhas_many :collections, dependent: :destroy
  • 那么为什么设计需要 user_id(因为它已经存在于其父集合中)?
  • 在一个页面上,我正在显示所有设计,并且我试图将用户名与该设计相关联。
  • 酷。 Design 类中的实例方法怎么样?...类似于:def user_name; collection.user.name; end

标签: ruby-on-rails


【解决方案1】:

create 方法应该有这个(这就是答案)

def create
  @collection = current_user.collections.find(params[:collection_id])
  @design = @collection.designs.new(design_params)
  @design.user = current_user
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-24
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    • 2018-09-03
    • 1970-01-01
    相关资源
    最近更新 更多