【问题标题】:Rails model nested forms, how to create foreign key in 2 modelsRails模型嵌套表单,如何在2个模型中创建外键
【发布时间】:2017-07-13 09:20:12
【问题描述】:

我正在尝试为我在学校的项目制作一个网页,用户可以在其中列出他或她拥有的股票并可以查看每周价格(我知道,不是最佳更新频率)

我已经设法让chartkickcharjs 在我的rails 应用程序中工作,但我意识到缺少一些东西。我试图绘制出我的模型以显示价格变化。

目前我有以下型号:

用户

has_many :investment_stocks
has_many :investment_price

投资股票

belongs_to :user
belongs_to :investment_price 
belongs_to :advisor  

投资价格

has_many :investment_stocks
has_many :users, through: :investment_stocks

迁移

投资价格

t.string :name
t.string :price
t.date :date

我的想法是手动更改每个可以在图表上引用和显示的股票的investment_price.price。但是对于有很多股票的用户,我想知道我的表格是否需要其他东西,因为 chartkickchartjs 的工作方式是我似乎需要在图表上显示 3 个变量,但我似乎总是能够仅在 2 左右工作

编辑

所以现在我有以下内容

用户模型

has_many :investment_stocks
has_many :investment_prices

Investment_stock 模型

belongs_to :user
has_many :investment_prices, dependent: :destroy
accepts_nested_attributes_for :investment_prices

投资价格模型

belongs_to :investment_stock, optional: true
belongs_to :user, optional: true

但我很难以嵌套形式添加在invest_stock 和invest_price 表上创建user_id

investment_stocks 控制器

def new
@investment_stock = InvestmentStock.new
@investment_stock.investment_prices.build
end

def create
@investment_stock= InvestmentStock.new(investment_stock_params)
@investment_stock["user_id"]= current_user.id 

如何使 user_id 同时出现在股票和价格表上?

【问题讨论】:

    标签: ruby-on-rails model chartkick


    【解决方案1】:

    好的,我想你可以试试: Investment_price 模型-> belongs_to :investment_stocks, belongs_to :user 。 股票有价格,用户有股票和价格。

    【讨论】:

    • 请添加一个有价值的链接,使这个答案更有用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多