繁体   English   中英

Rails 3 has_one / has_many问题

[英]Rails 3 has_one/has_many question

我正在编写一个包含具有多个表和联接表的数据库的应用程序,以此类推...我目前正在使用的两个表(我被困在上面)和我的模板表。

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

页面模型:

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

为何没有出现最后选择?

在此先感谢您提供的所有帮助!

编辑:

解决该问题所需要做的就是将Model逻辑放入控制器中,然后在视图中调用该对象,此方法就可以了

控制器:

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 ] }) %>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM