在rails中实现pinterest (一组对象)中的棋盘之类的东西的最佳方式是什么?我正在尝试使用它,它看起来更像是一个数组实现。这是我的关联逻辑:用户有很多集合,用户有很多引脚,集合属于用户。
用户类
class User < ActiveRecord::Base
has_many :pins, through: :collections
has_many :collections
end Pins类
class Pin < ActiveRecord::Base
belongs_to :user
has_many :collections
endCollection类
class Collection < ActiveRecord::base
belongs_to :user
end所以现在我的困惑是,如何实现一个控制器,它允许我创建一个集合,并在这个集合对象中创建或推送管脚,并将它们保存为current_user的另一个对象。希望我说得有道理
这是控制器
class CollectionsController < ApplicationController
def create
@collection = current_user.collections.new(params[:collection])
#this where i'm confused , if it an array , how to implement it , to push or create a pin object inside ?
end
end发布于 2013-06-19 01:42:30
为此,您必须使用嵌套属性。
检查此http://currentricity.wordpress.com/2011/09/04/the-definitive-guide-to-accepts_nested_attributes_for-a-model-in-rails-3/。
基本上你需要的是:
# collection model
accepts_nested_attributes_for :pins
# view, see also nested_form in github
f.fields_for :pins发布于 2013-06-19 01:54:02
您要查找的是has_many_through协会。请参阅Rails指南中的第2.4节:http://guides.rubyonrails.org/association_basics.html
class User < ActiveRecord::Base
has_many :collections
end
class Pin < ActiveRecord::Base
has_many :collections, through: :pinnings
end
class Pinning < ActiveRecord::Base
belongs_to :pin
belongs_to :collection
end
class Collection < ActiveRecord::base
belongs_to :user
has_many :pins, through: :pinnings
endhttps://stackoverflow.com/questions/17174641
复制相似问题