相关疑难解决方法(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万
查看次数

Rails has_many:通过嵌套表单

我刚刚加入has_many :through联盟.我试图实现保存所有3个表数据(的能力Physician,Patient通过一个单一的形式和关联表).

我的迁移:

class CreatePhysicians < ActiveRecord::Migration
  def self.up
    create_table :physicians do |t|
      t.string :name
      t.timestamps
    end
  end
end

class CreatePatients < ActiveRecord::Migration
  def self.up
    create_table :patients do |t|
      t.string :name
      t.timestamps
    end
  end
end

class CreateAppointments < ActiveRecord::Migration
  def self.up
    create_table :appointments do |t|
      t.integer :physician_id
      t.integer :patient_id
      t.date :appointment_date
      t.timestamps
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

我的模特:

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, :through => :appointments
  accepts_nested_attributes_for :appointments
  accepts_nested_attributes_for :physicians
end
class Physician …
Run Code Online (Sandbox Code Playgroud)

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

22
推荐指数
3
解决办法
2万
查看次数