Rails 3 has_one/has_many问题

问题描述:

我正在写一个应用程序,它包含一个包含多个表的数据库和连接表等等...我正在使用的两个(并且难以对付)是我的页表和我的模板表。Rails 3 has_one/has_many问题

现在一个页面只能包含一个模板,但一个模板可以有很多页面。

模型页:

class Page < ActiveRecord::Base 
    has_one :template 
    accepts_nested_attributes_for :template 
end 

模型模板:

class Template < ActiveRecord::Base 
    has_many :pages 
end 

当用户创建一个网页,我希望他们能够选择布局,但由于某种原因选择列表显示不作秀

HTML:

<%= form_for(@page) do |page| %> 
    <% if @page.errors.any? %> 
    <div id="error_explanation"> 
     <h2><%= pluralize(@page.errors.count, "error") %> prohibited this page from being saved:</h2> 

     <ul> 
     <% @page.errors.full_messages.each do |msg| %> 
     <li><%= msg %></li> 
     <% end %> 
     </ul> 
    </div> 
    <% end %> 

    <div class="field"> 
    <%= page.label "Page title" %><br /> 
    <%= page.text_field :slug %> 
    </div> 
    <div class="field"> 
    <%= page.label :active %>?<br /> 
    <%= page.check_box :active %> 
    </div> 

    <%= page.fields_for :category do |cat| %> 
     <%= cat.label :category %> 
     <%= select :page, :category_id, Category.find(:all).collect{|c| [c.name, c.id] } %> 
    <% end %> 

    <%= page.fields_for :template do |temp| %> 
     <%= temp.label :template %> 
     <%= select :page, :template_id, Template.find(:all).collect{|t| [t.content, t.id] } %> 
    <% end %> 

    <div class="actions"> 
    <%= submit_tag %> 
    </div> 
<% end %> 

为什么上次选择不显示的原因?

在此先感谢您的帮助!

编辑:

我不得不这样做来解决这个问题,制定这样的模型逻辑在我的控制器,然后调用视图该对象和它的工作

控制器:

def new 
    @page = Page.new 
    @categories = Category.find(:all) 
    @templates = Template.find(:all) 

    respond_to do |format| 
     format.html # new.html.erb 
     format.xml { render :xml => @page } 
    end 
    end 

查看:

<div class="field"> 
     <%= page.label :template %> 
     <%= page.select("template_id", @templates.collect { |t| [t.content, t.id] }, :include_blank => 'None') %> 
    </div> 

希望这可以帮助别人!

首页可能 “属于” 模板:

class Page < ActiveRecord::Base 
    belongs_to :template 
    accepts_nested_attributes_for :template 
end 

,而不是和:

<%= page.fields_for :template do |temp| %> 
    <%= temp.label :template %> 
    <%= select :page, :template_id, Template.find(:all).collect{|t| [t.content, t.id] } %> 
<% end %> 

我会用一个简单的collection_select:

<%= page.select("template_id", Template.all.collect {|t| [ t.contet, t.id ] }) %> 
+0

现在我得到这个错误:未定义的方法'所有'的ActionView ::模板︰类 – dennismonsewicz 2010-10-14 13:06:46

+0

我想通了我的问题!我会在上面的解决方案 – dennismonsewicz 2010-10-14 14:33:07