我正在开发具有这些类的rails应用程序..
很多股票都有..
=>许多TIME_DELTAS
现在我刚刚创建了一个分支并为应用程序添加了设计。现在,我希望每个用户都能拥有自己的库存对象,而不是他们的共享数据库,但是用户特定的库存在他们自己的私有会话中拥有自己的库存。
我是否正确地假设这样做我需要使股票成为嵌套的用户类,以便每个用户都拥有自己的股票?他们是一个轻松做到这一点的指南吗?谢谢!
索引
def index
if current_user
@stocks = current_user.stocks
else
redirect_to new_user_session_path, notice: 'You are not logged in.'
end
end
创建
def create
# XXX Add columns for delta and current standing when we get there
# they can intiate to nil
# params['stock'][:user] = current_user
@stock = Stock.new(stock_params)
@stock.user = current_user
if @stock.save
redirect_to @stock
else
render 'new'
end
end
更新
def update
@stock = find_stock
if @stock.update(stock_params)
redirect_to @stock
else
render 'edit'
end
end
SERVERLOG
开始发布" / stock"对于2014.0-04 15:25:15 -0700的127.0.0.1 由StocksController处理#create as HTML参数: {" UTF8" = GT;"✓&#34 ;, " authenticity_token" = GT;" AvtGUf + gPXnpMHNASQK74G + f97Ho4YxkUDEfl + lhZQg =&#34 ;, " stock" => {" name" =>" Google","#sha;#34; =>" goog&#34 ;},"用户" =>" 2", "提交" =>"创建股票"}用户加载(0.9ms)SELECT"用户"。* FROM "用户"用户"。" id" = 2 ORDER BY"用户"。" id" ASC限制1
(0.0ms)开始交易股票存在(0.1ms)SELECT 1 AS one 来自"股票"在哪里"股票"。"#标签" =' goog'限制1股票存在 (0.1ms)选择1作为一个来自"股票"在哪里"股票"。"名称" = '谷歌' LIMIT 1(0.0ms)回滚事务已完成500 6ms内部服务器错误NoMethodError(未定义的方法
attributes' for nil:NilClass):
创建'
app/controllers/stocks_controller.rb:21:in渲染 /Users/nathanielmots/.gems/ruby/2.1.0/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.6ms)呈现 /Users/nathanielmots/.gems/ruby/2.1.0/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.2ms)呈现 /Users/nathanielmots/.gems/ruby/2.1.0/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.1ms)呈现 /Users/nathanielmots/.gems/ruby/2.1.0/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb救援/布局(13.5ms)
答案 0 :(得分:0)
class User < ActiveRecord::Base
has_many :stocks
end
class Stock < ActiveRecord::Base
belongs_to :User
end
答案 1 :(得分:-1)
要在1-M relationship
和User
型号之间设置Stock
,您需要按照以下建议定义关联:
class User < ActiveRecord::Base
has_many :stocks
## ...
end
class Stock < ActiveRecord::Base
belongs_to :user
## ...
end
在此之后在user_id
表中创建一个foreign_key stocks
,如下所示:
通过运行以下内容生成用于向user_id
表添加stocks
引用的迁移:
rails generate migration AddUserRefToStocks user:references
此次运行后rake db:migrate
注意:
使股票成为嵌套的用户类,以便每个用户都拥有自己的股票?
Ruby中没有嵌套类这样的东西。您的意思可能是如何设置User
和Stock
类之间的关联。
<强>更新强>
更改new
中的create
和StocksController
行为,如下所示:
def new
@stock = current_user.stocks.build
end
def create
@stock = Stock.new(stock_params)
if @stock.save
redirect_to @stock, notice: 'Stock was successfully created.'
else
render 'new'
end
end
另外,在form_for
的{{1}}视图中添加隐藏字段(new
内),如下所示:
stocks
注意:请确保<%= f.hidden_field :user_id %>
方法中permit
字段为user_id
。