我有两个模型:User和Purchase。采购属于用户。
class User < ApplicationRecord
has_many :purchases
end
class Purchase < ApplicationRecord
belongs_to :user
enum status: %i[succeeded pending failed refunded]
end
在Rails 5.2中,当对没有关联Purchase的User进行任何修改时,都会引发验证错误。这对于新的采购非常有用,但是当简单地试图用数据库中不再存在的用户保存现有采购的数据时,它也会引发
我有一个赞助商模型和一个宣传代码模型。
赞助商可以拥有零或更多的广告代码。
一个广告代码可以有0或一个赞助商。
因此,一个promo代码应该有一个对发起者的可选引用,也就是一个可能有值也可能没有值的sponsor_id。我不知道如何在Rails中设置它。
到目前为止,我的情况如下:
# app/models/sponsor.rb
class Sponsor < ActiveRecord::Base
has_many :promo_codes # Zero or more.
end
# app/models/promo_code.rb
class PromoCode
我正在尝试将创建的注释连接到current_user。我有一个模型comment,它是一个多态关联。
class CreateComments < ActiveRecord::Migration[6.0]
def change
create_table :comments do |t|
t.string :content
t.references :commentable, polymorphic: true
t.timestamps
end
end
end
在控制器中,我试图连接@comment.user = current_
这一定是很常见的情况,但我搞不懂:
我有一个多态评论模型,一个Post模型和一个用户模型。这是我的协会设置:
class Post < ActiveRecord::Base
has_many :comments, :as => :commentable
end
class User < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
attr_accessible :content
belongs_to :commentable, polymo
我有用户,帖子和评论。用户只能对每个帖子发表一条评论。
class User < ActiveRecord::Base
has_many :posts
has_many :comments
end
class Post < ActiveRecord::Base
has_many :comments
belongs_to :user
end
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :post
end
在用户页面(例如http://host/users/1)上,我想显
我正在学习rails并尝试多态关联。我在下面列出了几个简单的模型来进行说明。模型关联似乎像预期的那样工作得很好。但是,如果一个用户(评论者)想要给另一个用户留下评论呢?我似乎不能让它在这些配置下工作。我该怎么做呢?
class User < ApplicationRecord
# username, email, password_digest
has_many :comments, as: :commentable, dependent: :destroy
end
class Project < ApplicationRecord
# title, complet
我正在尝试使用user.comments访问来自给定用户的所有评论。查询将经历两个不同的模型,这两个模型都可能返回结果。我的关系设置如下:
class User < ActiveRecord::Base
has_many :organisers
has_many :participants
has_many :comments, through: :participants / :organisers (see explenation below)
end
class Organiser < ActiveRecord::Base
belongs_to :user
当我通读和它的相关链接时,Ecto似乎支持多态关联。
假设我需要一个任务和事件模型的注释模型关联。如果我对Ecto与自定义源代码的关联的理解是正确的,那么我们需要四个表和三个模型,
表格
taskseventstasks_commentsevents_comments
模型
TaskEventComment
任务和事件模型将具有与自定义源的has_many关联,如下所示。
defmodule ExampleApp.Task do
use ExampleApp.Web, :model
schema "tasks" do
field :title, :string