簡體   English   中英

所屬屬性的嵌套屬性

[英]Nested attributes for belongs_to relationship

我有這個引腳模型:

class Pin < ActiveRecord::Base
  belongs_to :user
  belongs_to :image
  accepts_nested_attributes_for :image
  attr_accessible :image_attributes
end

我有這個圖像模型:

class Image < ActiveRecord::Base
  has_many :pins
   validates_attachment_presence :attachment
   validates_attachment_size :attachment, :less_than => 5.megabytes
   validates_attachment_content_type :attachment, :content_type => ['image/jpeg', 'image/png']
   accepts_nested_attributes_for :pins
   attr_accessible :pins_attributes
end

為了創建一個新的Pin,我想對圖像使用嵌套屬性,但是它不起作用:我在控制器和視圖文件中使用的代碼是:

def new
    @pin = Pin.new
    @pin.build_image if @pin.build_image.nil?
end

 def create
  @pin = Pin.new(params[:pin])
   @pin.user_id  = session[:user_id]
  respond_to do |format|
    if @pin.save
      format.html { redirect_to(@pin, :notice => 'Pin was successfully created.') }
      format.xml  { render :xml => @pin, :status => :created, :location => @pin }
    else
      @boards = User.find(session[:user_id]).boards
      format.html { render :action => "new" }
      format.xml  { render :xml => @pin.errors, :status => :unprocessable_entity }
    end
  end
end

並在視圖文件中:

   <%= form_for @pin,:html=>{ :multipart => true} do |f| %>
    <% if @pin.errors.any? %>
    <div id="error_explanation">
        <h2><%= pluralize(@pin.errors.count, "error") %> prohibited this pin from being saved:</h2>

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



    <div class="field">
        <%= f.label :title %>
        <%= f.text_area :title %>
    </div>
    <%= f.fields_for :image do |f_i| %>
    <div class="field">
        <%= f_i.label :attachment %>
        <%= f_i.file_field :attachment %>
    </div>
    <% end %>
    <div class="actions">
        <%= f.submit %>
    </div>
    <% end %>

所有的時間形式都會呈現錯誤:

     Image attachment file name must be set.

我會說問題attr_accessible :pins_attributes在Image模型中的attr_accessible :pins_attributes和Pin模型中的另一個attr_accessible。 通常,除id以外的所有屬性都是可訪問的(方法可以批量分配),但是如果您將某個屬性聲明為可訪問的,則必須列出要批量分配的所有屬性。 因此,嘗試列出兩個模型中的屬性,或者只是設置attr_accessible :all

在圖像模型中,我需要指定

  has_attached_file :attachment, :styles => { :small => "150x150>" }

我的錯 :(

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM