Ruby on rails 多个t.reference使用嵌套模型得到nil
我正在为用户使用Desive User.rbRuby on rails 多个t.reference使用嵌套模型得到nil,ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4,ruby-on-rails-3.2,Ruby On Rails,Ruby On Rails 3,Ruby On Rails 4,Ruby On Rails 3.2,我正在为用户使用Desive User.rb belongs_to shop has_many tasks has_many users has_many tasks belongs_to user belongs_to shop Show.rb belongs_to shop has_many tasks has_many users has_many tasks belongs_to user belongs_to shop 任务.rb belongs_to shop has_m
belongs_to shop
has_many tasks
has_many users
has_many tasks
belongs_to user
belongs_to shop
Show.rb
belongs_to shop
has_many tasks
has_many users
has_many tasks
belongs_to user
belongs_to shop
任务.rb
belongs_to shop
has_many tasks
has_many users
has_many tasks
belongs_to user
belongs_to shop
创建新任务时:
current_user.tasks.create(...)
当我需要与用户相同时,shop\u id
获取nil的值
当我创建新任务时
current_user.shop.tasks.create(...)
我得到的用户id为nil,但得到了商店id的正确值
我错过了什么
提前谢谢。什么时候
current_user.tasks.create(...)
除非您显式发送,否则is run rails关联不会知道它必须填充shop_id
current_user.tasks.create(shop_id: current_user.shop.id)
反过来也一样。对于这种情况,您可以使用更好的建模方法,在用户、商店和任务之间建立多态关联。更多的细节和例子可以在这里找到
看
不要认为这与designe有关。在当前用户.shop.tasks.create(…)
中创建(…)
您直接在任务集合上调用创建,以获得单个商店
。这实际上相当于:
Shop.find_by(user_id: current_user.id).tasks.create(...)
商店可能有多个用户,因此在该语句中没有明确说明新创建的任务应该属于当前用户
我认为最简单的解决方案是自己创建任务,显式设置两个外键:
Task.create(shop_id: current_user.shop_id, user_id: current_user.id)
尽管您必须重新加载用户
和商店
参考,以获取新关联的任务
如果您想要更自动化的东西,考虑使用关联回调在<代码> HasyMule:任务< <代码> >用户>代码> >代码>任务> <代码> >从<代码>用户< /代码>的商店ID:< /p>
class user < ActiveRecord::Base
belongs_to :shop
has_many :tasks, before_add: :assign_to_shop
def assign_to_shop(task)
task.shop = self.shop
...
end
end
class用户
设计当前用户
方法返回用户的相同对象
# simple example
def sign_in
session[:current_user] = User.find_by_email(params[:email])
end
def current_user
session[:current_user]
end
若用户已登录,则当前用户的方法应能正常工作,如下图所示
#1
current_user.tasks.create(...)
#2 you can also like this
t = Task.new(...)
t.user_id = current_user.id
t.save
您可以在rails控制台
中播放,很容易理解
current_user = User.first
current_user.tasks.create(...)
你试过在rails控制台中运行吗?
?是的,结果相同。你能试试这个User.first.tasks.create(…)
?现在不知何故,它工作了!!!!!把它贴出来作为一个答案或什么的,我会把它标记出来。这只在控制台中起作用,奇怪!我什么也没改变,这只在控制台上起作用,不知怎的它停止了。我知道这听起来很疯狂,但没错@KamalG'ool你登录了吗?我登录了,我在控制器中修复了这个问题,每次根据当前用户创建、分配店铺和用户时,我都会在稍后发布一个答案。