通过has_one / belongs_to将模型ID保存为外键

时间:2014-02-13 07:01:19

标签: mysql ruby-on-rails ruby associations

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

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

目前,在我的税务模型中,create函数看起来像这样:

class Tax < ActiveRecord:Base
belongs_to :user


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

然后在taxes_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有关(设计) )。目前,我的设置工作正常,除了在用户模型列“tax_id”中保存税模型ID,就像我说的那样。

我想知道我是否需要在belongs_to或has_one语句中添加外键ID,即使我认为只要列名为{{{},我就会自动生成“链接”。 1}}

1 个答案:

答案 0 :(得分:1)

尝试使用

user.build_tax

我认为这可能会帮助你。

has_many关联的构建语法:

user.taxes.build

has_one关联的构建语法:

user.build_tax  # this will work

user.tax.build  # this will throw error
相关问题