相关疑难解决方法(0)

Rails嵌套表单与has_many:through,如何编辑连接模型的属性?

使用accepts_nested_attributes_for时如何编辑连接模型的属性?

我有3个模型:由连接器加入的主题和文章

class Topic < ActiveRecord::Base
  has_many :linkers
  has_many :articles, :through => :linkers, :foreign_key => :article_id
  accepts_nested_attributes_for :articles
end
class Article < ActiveRecord::Base
  has_many :linkers
  has_many :topics, :through => :linkers, :foreign_key => :topic_id
end
class Linker < ActiveRecord::Base
  #this is the join model, has extra attributes like "relevance"
  belongs_to :topic
  belongs_to :article
end
Run Code Online (Sandbox Code Playgroud)

所以当我在主题控制器的"新"动作中构建文章时......

@topic.articles.build
Run Code Online (Sandbox Code Playgroud)

...并在topics/new.html.erb中创建嵌套表单...

<% form_for(@topic) do |topic_form| %>
  ...fields...
  <% topic_form.fields_for :articles do |article_form| %>
    ...fields...
Run Code Online (Sandbox Code Playgroud)

... Rails自动创建链接器,这很棒. 现在我的问题是:我的链接器模型还具有我希望能够通过"新主题"表单更改的属性.但是Rails自动创建的链接器除了topic_id和article_id之外,其所有属性都有nil值.如何将其他链接器属性的字段放入"新主题"表单中,这样它们就不会出现?

nested join ruby-on-rails nested-forms

103
推荐指数
2
解决办法
4万
查看次数

Rails4中的嵌套简单表单 - 有很多通过,保存多个记录

通过关系,我有一个标准的has_many.人类通过连接表交互有许多兽人.互动只是一个表格和模型; 没有控制器或视图.

使用Rails 4中的simpleform gem,我想从人体页面创建一个表单,以便从所有兽人的池中选择多个兽人.提交后,我希望它在交互表中创建/更新尽可能多的记录,每个记录都包含人工ID,并且选择了多个orc ID.:

AKA列表符号

  1. 从一端制作表格(人类)
  2. 列出表格中的所有兽人
  3. 从该列表中选择多个兽人
  4. 将多个记录保存到交互表中,human_id并且orc_id从该列表中选择兽人.(human_id在这些记录中将是相同的,因为它从给定的人类表单页面开始)

我将尽可能多地编写整个故事的代码.请随时要求澄清,并解决任何错误,以实现这一点.

humans
  integer "id"

interactions
  integer "human_id"
  integer "orc_id"


  index ["human_id", "orc_id"] 
  # This is the primary key. no normal id.
  # Is it better to have a primary id for this join table, or does it not matter?

orcs
  integer "id"
Run Code Online (Sandbox Code Playgroud)

楷模

/models/human.rb

class Human < ActiveRecord::Base
  has_many :interaction
  has_many :orcs, through: :interactions

  accepts_nested_attributes_for :interactions
end
Run Code Online (Sandbox Code Playgroud)

/models/interaction.rb

# Purely a join model and …
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails nested-forms has-many-through simple-form

3
推荐指数
1
解决办法
1629
查看次数