【问题标题】:Save model id as foreign key through has_one / belongs_to通过 has_one/belongs_to 将模型 id 保存为外键
【发布时间】:2014-02-13 07:01:18
【问题描述】:

我将简要解释一下我的情况:我有一个名为“tax”的模型,它属于一个“用户”,其中一个“用户”拥有一个。

在我的用户表中,我有一个名为“tax_id”的列,我想在用户创建税收模型时存储它的 ID。

目前,在我的税务模型中,create 函数如下所示:

class Tax < ActiveRecord:Base
belongs_to :user


tax = Tax.new(income: income, taxes: taxes, rrsp: rrsp)
tax.save

然后在 tax_controller 文件中,create 函数如下所示:

def create
    @tax = Tax.new(secure_params)
    @tax.user = User.find(current_user.id)
    if @tax.save
    redirect_to show_tax_path(current_user.tax)
  else
    render :new
  end
  end

(secure_params) 是在私有定义中设置的字段输入的强参数。

现在,有人提到如果我使用build 可能会更好,但不幸的是我根本无法让它工作,这与我如何使用current_user(设计)有关。目前,我的设置工作正常,除了像我说的那样将税收模型 ID 保存在用户模型列“tax_id”中。

我想知道我是否可能需要在belongs_to 或has_one 语句中添加一个外来ID 键,尽管我的印象是只要列被命名为@987654325,就应该自动创建“链接” @

【问题讨论】:

  • 既然 tax belongs_to 用户,为什么你在 users 表中添加属性 tax_id。相反,您应该在税表中添加 user_id 属性
  • @arivarasan 我确实在 tax 表中有 user_id,但我想要一个双向关系,以便 tax_id 也保存在 users 表中

标签: mysql ruby-on-rails ruby associations


【解决方案1】:

尝试使用

user.build_tax

我认为这可能会对您有所帮助。

has_many 关联的构建语法:

user.taxes.build

has_one 关联的构建语法:

user.build_tax  # this will work

user.tax.build  # this will throw error

【讨论】:

  • 对构建语法的确切放置位置感到困惑?它会在控制器的create方法中的@tax.user = User.find(current_user.id)下,还是会替换模型中的整个方法tax = Tax.new(income: income, taxes: taxes, rrsp: rrsp)
  • 我不知道您为什么在模型中使用此方法,而您可以在用户的​​“新”方法中使用它,然后在用户的相同“新”方法中使用“user.build_tax” "
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
相关资源
最近更新 更多