我在Rails 5.1API应用程序中有如下所示的Post和Comment模型
Post
class Post < ApplicationRecord
has_many :comments
end
注释
class Comment < ApplicationRecord
belongs_to :post
end
**后序列化程序(使用ActiveModel序列化程序)**
class PostSerializer < ActiveModel::Serializer
attributes :id, :title, :text, :created_at
我有一个项目资源和一个所有者资源。
rails g scaffold Item name:string
rails g scaffold Owner name:string
class Item < ActiveRecord::Base
has_one :owner
accepts_nested_attributes_for :owner
end
class Owner < ActiveRecord::Base
belongs_to :item
end
我的问题是我不能创建引用现有所有者对象的新Item对象。
In /db/migrate/create_owners
使用以下型号:
class Location < ActiveRecord::Base
has_many :group_locations
has_many :groups, :through => :group_locations
accepts_nested_attributes_for :group_locations
end
class GroupLocation < ActiveRecord::Base
belongs_to :group
belongs_to :location
end
class Group
我只创建了一个rails api应用程序。这些模型之间的联系如下:
class Book < ApplicationRecord
has_and_belongs_to_many :authors
accepts_nested_attributes_for :authors, allow_destroy: true
end
class Author < ApplicationRecord
has_and_belongs_to_many :books
end
现在,当我试图用邮递员发布的参数创建一个新的Book时,
{
"book": {
我有一个模型B,它的主键id不自动递增(因为它的值是来自另一个系统的guids )。
当我试图通过设置嵌套属性来创建B的新实例时,会出现一个错误:
ActiveRecord::RecordNotFound: Couldn't find B with ID=076dda41-afa6-4324-b6fd-219d99089dfc for A with ID=846205
a.attributes = {
b_attributes: {
id: '076dda41-afa6-4324-b6fd-219d99089dfc'
}
}
当我指定id时,如何使赋值构
hello body可以帮助我在rails中执行一个post请求,以便在json中的不同表中保存倍数记录和sabe数据。
{
"post":
{
"title":"Titlea 2",
"body":"body of the post 2"
}
"comment":[
{
"title":"Title 2",
"body":"body of the post 2"
在Rails 3.2应用程序中,我有一个简单的关联
class Element < ActiveRecord::Base
has_many :categories
end
class Category < ActiveRecord::Base
belongs_to :element
validates :name, uniqueness: true
end
和下面的代码
element = Element.find_or_initialize_by_name(elem_name)
element.categories = cat_names.map { |name|
我正在尝试将数据库记录转换为可导出的文档,这样我就可以重新导入它并更新数据库。我只使用CSV,但它也是嵌套的,乡村has_many省has_many城市说。
我试过把YAML卖给每个
File.open("#{RAILS_ROOT}/lib/tasks/canada.yml", 'w') do |file|
country = Country.find(1)
country.provinces
country.cities
YAML::dump(country, file)
end
但当我装货的时候,它没有:
country = YAML.loa
ActiveRecord似乎不明白,给定一组具有嵌套属性的现有记录的参数,它可以创建一个新的嵌套记录,该记录本身有一个嵌套的现有记录。(关系树:Existing -> New -> Existing)
这是个窃听器还是我漏掉了什么?
让我给你们举个简单的例子。
以下是我的模特:
class User < ActiveRecord::Base
has_many :posts
attr_accessible :name, :posts_attributes
accepts_nested_attributes_for :posts
end
class Post <
也许我遗漏了一些明显的东西(希望如此),但我在以嵌套形式保存记录时遇到了一个奇怪的问题。这是一个非常基本的设置,在我的LineItem模型是一个两个词的关系(:line_items)方面有一点小的复杂性。然而,我遵循了Rails的指导方针,它似乎工作得很好。
我的fixtures正在创建line_items和发票之间的正确关系,所有内容都在我的视图中正确显示,但是我无法正确保存任何line_item记录(在我的Rails控制台或视图中)。
class Invoice < ActiveRecord::Base
attr_accessible :line_items #and the
当我从UI中传递值时,我得到了不允许的params。模型之间的联系是多到多的。
class User < ApplicationRecord
has_many :user_posts
has_many :posts, through: :user_posts
end
class Post < ApplicationRecord
has_many :user_posts
has_many :users, through: :user_posts
accepts_nested_attributes_for :user_posts
end