创建可以在 Rails 中的多个控制器中定义和访问的变量
我正在创建一个用于创建多个待办事项列表的应用程序。因此,用户登录后有多个列表,每个列表包含多个项目。其他一切都正常,但我正在努力创建这些项目。
我在列表上创建新项目的代码(可以在 items_controller
中找到)是:
def create
@list =
@new_item = @list.items.build(params[:item])
if @new_item.save
flash[:success] = "Item saved!"
end
redirect_to root_path
end
问题是,我不确定如何定义 @list
应该是。我有一个变量 current_user
(基于会话)用于创建新列表,但每个会话只有一个用户,每个会话有多个列表,所以我不能只复制该方法。
基本上,我一直致力于如何让该项目知道它属于哪个列表(应该是我刚刚所在的显示页面的列表)。在Java中,我有一个静态变量,每次进入列表时我都会重新定义它,但我尝试这样做,但它不起作用,而且我在rails中读到的显然不起作用。
I'm creating an app for creating multiple to-do lists. So a user signs in, has multiple lists, and each list contains multiple items. Everything else is working, but I'm struggling to create the items.
My code for creating a new item on a list (this is found in the items_controller
) is :
def create
@list =
@new_item = @list.items.build(params[:item])
if @new_item.save
flash[:success] = "Item saved!"
end
redirect_to root_path
end
And the issue is, I'm not sure how to define what @list
should be. I have a variable current_user
(based on the session) for creating a new list, but there is only one user per session and multiple lists per session, so I can't just replicate that method.
Basically, I'm stuck on how to be able to have the item know which list it belongs to (which should be the list whose show page I was just on). In Java I'd have a static variable that I would redefine every time I went to a list, but I tried doing that and it didn't work, and I read that apparently in rails that doesn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该使用 url 参数来跟踪列表,而不是存储变量。您需要修改表单以包含
list_id
参数。然后在控制器中,当您创建列表项时,执行以下操作:或者,如果您使 params 包含
items[list_id]
参数,那么在 Rails 中,可以在params[ :item][:list_id]
所以你应该能够这样做:如果你以第二种方式这样做,只需确保在 ListItem 模型中添加验证以保证
list_id
存在并列出它指向存在。Rather than storing a variable, you should keep track of the list using url parameters. You will need to modify your form to include a
list_id
parameter. Then in the controller when you are creating a list item, do something like:Or if you made your params include an
items[list_id]
parameter, then in Rails it will be accessible inparams[:item][:list_id]
so you should just be able to just do:If you do it this second way, just be sure to add a validation in the ListItem model to guarantee that
list_id
is present and the list it points to exists.listItem 应具有列表模型的外键,列表模型应具有帐户的外键。通过这种方式,您应该能够轻松地遍历该结构。
The listItem should have a foreign key to the list model, and the list model should have a foreign key to the account. In this way you should be able to traverse the structure easily.