2016-01-24 45 views
1

我有这样轨nasted模型形式

post.rb

标题模型关联:字符串描述:文本

class Post < ActiveRecord::Base 

    belongs_to :user 
    has_many :items 
    accepts_nested_attributes_for :items 

end 

item.rb的

post_id:整数次序:整数

class Item < ActiveRecord::Base 
    belongs_to :post 
    has_one :link 
    has_one :movie 
    has_one :photo 
    has_one :quate 
end 

链接,电影,照片,quate.rb

link.rb:ITEM_ID:整数网址:字符串URL文本:字符串

movie.rb:ITEM_ID :整数youtube-url:string

photo.rb:item_id:integer image:string comment:string titl E:字符串

quate.rb:ITEM_ID:整数quate:串Q-网址:串Q-标题:串

belongs_to :item 

我想建立用户后通过应用Ruby on Rails的。 项目模型有订单栏,所以用户可以选择和添加任何电影,链接,照片来建立自己的帖子。

我该如何为这些模型创建表单?

+0

Rails的演员有很大的插曲是:HTTP:// railscasts的.com /次/ 196-嵌套模型外形修订。我相信你必须是一个观看那个的订阅者,但是较老的一个可以自由观看:http://railscasts.com/episodes/196-nested-model-form-part-1 – user2884789

+0

你的意思是“讨厌的模型” ? – sawa

+0

有人将所有专业版本上传到YouTube:https://www.youtube.com/watch?v = amT27SfNhKM –

回答

0

这可能不像您需要的那样定义;如果需要,我会删除。

您有一个巨大的antipattern与您的belongs_to模型。他们看起来像他们代表一个单独的数据集,我会用enum来区分他们的状态将它们合并到Item模型:

#app/models/item.rb 
class Item < ActiveRecord::Base 
    #schema id | post_id | state | url | title | comment | created_at | updated_at 
    belongs_to :post 
    enum state: [:link, :movie, :photo, :quate] 
end 

这会给你创造的Item实例的能力,你然后可以分配不同的“状态”:

@item = Item.new 
@item.state = :link 

虽然这意味着改变你的模式,它可以让你直接存储items每个post的能力(而不是^ h AVING与另一个模型添加它们):

#app/controllers/posts_controller.rb 
class PostsController < ApplicationController 
    def new 
     @post = Post.new 
     @post.items.build 
    end 

    def create 
     @post = Post.new post_params 
     @post.save 
    end 

    private 

    def post_params 
     params.require(:post).permit(items_attributes: [:state, :url, :title, :comment]) 
    end 
end 

#app/views/posts/new.html.erb 
<%= form_for @post do |f| %> 
    <%= f.fields_for :items do |i| %> 
     <%= i.select :state, Item.states.keys.map {|role| [role.titleize,role]}) %> 
     <%= i.text_field :url %> 
     <%= i.text_field :title %> 
     <%= i.text_field :comment %> 
    <% end %> 
    <%= f.submit %> 
<% end %> 

您还需要确保你在你的Post模型有accepts_nested_attributes_for

#app/models/post.rb 
class Post < ActiveRecord::Base 
    has_many :items 
    accepts_nested_attributes_for :items 
end