首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么Rails不能拯救细木工模型?是正常行为还是bug?

为什么Rails不能拯救细木工模型?是正常行为还是bug?
EN

Stack Overflow用户
提问于 2012-05-05 01:19:49
回答 2查看 474关注 0票数 1

当我尝试这样做时,joiner模型没有被保存(假设为Account has_many :users, through: :roles,反之亦然):

代码语言:javascript
运行
复制
def new
  @account = current_user.accounts.build
end
def create
  @account = current_user.accounts.build(params[:account])
  @account.save # does not save the joiner model
end

这将创建@account,并在其中创建user_id=current_user.idaccount_id: @account.id的角色记录。仅保存@account。角色模型中没有记录。使用console得到的结果是一致的。

create操作中用current_user.accounts.create替换current_user.accounts.build,将保存joiner (角色记录)模型。因此,我不认为这是一个验证问题。我使用的是Rails 3.2.3。

型号:

代码语言:javascript
运行
复制
class User < ActiveRecord::Base
  has_many :roles
  has_many :accounts, through: :roles
end
class Account < ActiveRecord::Base
  has_many :roles
  has_many :users, through: :roles
  accepts_nested_attributes_for :users
end
class Role < ActiveRecord::Base
  attr_accessible
  belongs_to :users
  belongs_to :accounts
end

视图

代码语言:javascript
运行
复制
<%= simple_form_for(@account) do |f| %>      
  <%= render 'account_fields', f: f %>
  <%= f.submit %>
<% end %>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-05-19 01:53:16

票数 0
EN

Stack Overflow用户

发布于 2012-05-05 02:02:28

试着使用

更新:

代码语言:javascript
运行
复制
class User < ActiveRecord::Base
  has_many :roles
  has_many :accounts, through: :roles, :autosave => true
end

You can find more info about autosave here

或者在User模型中使用回调

代码语言:javascript
运行
复制
after_save :save_accounts, :if => lambda { |u| u.accounts } 

def save_accounts 
  self.accounts.save
end
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10453346

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档