簡體   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