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

has_many:通过问题

我之前使用过has_and_belongs_to_many,并已转换为has_many:through.以下是它如何查找可以让很多用户玩的游戏列表.有了这个,我可以做game.users和user.games ....:

class Game < ActiveRecord::Base
 has_many :game_users, :dependent => :destroy
 has_many :users, :through => :game_users, :uniq => true
end

class User < ActiveRecord::Base
 has_many :game_users, :dependent => :destroy
 has_many :games, :through => :game_users, :uniq => true
end

class GameUser < ActiveRecord::Base
  belongs_to :game
  belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)

我的连接表的数据库迁移:

create_table :game_users, :id => false do |t|
      t.column :game_id, :integer
      t.column :user_id, :integer
      t.column :player_index, :integer
    end
Run Code Online (Sandbox Code Playgroud)

我不太确定我得到了这一切,请帮我查一下我的事实:

  1. 依赖=>:destroy是否正确?如果游戏或用户被销毁,我希望删除'game_users'连接表条目 - 但我不希望删除用户如果删除游戏,反之亦然......?

  2. uniq字段应该表示游戏仅包含唯一用户,并且用户仅包含唯一游戏.那是对的吗?

  3. 像以前一样进行数据库迁移:id => false.这仍然是正确的做法吗?我试图在控制台中摧毁一个游戏,并对丢失的内容进行投诉......所以我猜不到并试图理解为什么.

我发现rails活动记录关联非常混乱.我想他们不应该是!

activerecord ruby-on-rails has-many-through

6
推荐指数
1
解决办法
3792
查看次数