代码之家  ›  专栏  ›  技术社区  ›  dennismonsewicz

Rails3有很多问题

  •  0
  • dennismonsewicz  · 技术社区  · 15 年前

    我正在编写一个应用程序,其中包含一个数据库,其中包含几个表和连接表等等。。。我目前正在处理的两个表是pages表和templates表。

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

    页面型号:

    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>
    

    希望这对其他人有帮助!

    1 回复  |  直到 15 年前
        1
  •  1
  •   Victor Hugo Bueno    15 年前

    第一页可以“属于”模板:

    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 %>
    

    我会使用一个简单的集合选择:

    <%= page.select("template_id", Template.all.collect {|t| [ t.contet, t.id ] }) %>
    
    推荐文章