[英]How do I create migrations for model attributes in rails
I'm having difficulty with bulding attributes within my model. 我在模型中难以建立属性时遇到困难。 I keep seeing this error 我一直看到这个错误
NoMethodError: undefined method `users' for #<ActiveRecord::ConnectionAdapters::SQLite3::TableDefinition:0x00007f9d9ad9df98>
I need attributes that look like this: 我需要看起来像这样的属性:
#group.rb
class Spree::Group < ActiveRecord::Base
has_many :users
end
#user_decorator.rb
Spree::User.class_eval do
belongs_to :group, class_name: "Spree::Group"
end
For group.rb I ran 对于group.rb我跑了
rails g model Spree::Group
and I got: 我得到:
class Spree::Group < ApplicationRecord
has_many :users
end
I'm confused on how to add 'has_many :users' without actually going into the model and inputting it there. 我对如何添加'has_many:users'而不真正进入模型并在那里输入感到困惑。
For the user_decorator I'm not sure what that migration would look like. 对于user_decorator,我不确定该迁移是什么样的。 Any help would be fantastic! 任何帮助都太棒了!
You could call: 您可以致电:
rails g model group user:references
which will generates an user_id column in the groups table and will modify the group.rb model to add a belongs_to :user relatonship. 这将在groups表中生成一个user_id列,并将修改group.rb模型以添加一个Emirates_to:user关系。 Please note, you must to put manually the has_many :groups or has_one :group relationship to the user.rb model. 请注意,您必须手动将has_many:groups或has_one:group关系添加到user.rb模型。
If you already have the model generated, you could create a migration with the following: 如果已经生成了模型,则可以使用以下内容创建迁移:
rails g migration AddUserToGroup user:belongs_to which will generate: rails g迁移AddUserToGroup user:belongs_to将生成:
class AddUserToGroup < ActiveRecord::Migration
def change
add_reference :groups, :user, index: true
end
end
the only difference with this approach is, the belongs_to :user relationship in the group.rb model won't be created automatically, so you must create it for your own. 这种方法的唯一区别是,不会自动创建group.rb模型中的belongs_to:user关系,因此您必须自己创建它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.