我遇到了一个麻烦,我是ROR的新手,想要使用嵌套属性为组织保存一些图像,或者为了简单起见只是一个字符串,以便尝试在数据库中保存嵌套属性,但实际上它没有保存。
组织模式
class Organization < ApplicationRecord
has_secure_password
has_many :needs, dependent: :destroy
has_many :org_images, dependent: :destroy
has_many :stringas, dependent: :destroy
accepts_nested_attributes_for :org_images, :reject_if => lambda { |t| t['org_image'].blank? }
accepts_nested_attributes_for :stringas, :reject_if => lambda { |t| t['stringa'].blank? }
模式
create_table "org_images", force: :cascade do |t|
t.string "caption"
t.integer "organization_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "photo_file_name"
t.string "photo_content_type"
t.integer "photo_file_size"
t.datetime "photo_updated_at"
end
create_table "stringas", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "organization_id"
end
组织控制器
def new
@organization = Organization.new
3.times {@organization.org_images.build}
@organization.stringas.build # added this
end
def organization_params
params.require(:organization).permit(:org_name, :email, :password, :info,:image, :website_URL, :contacts, :logo_url , :password_confirmation ,stringas_attributes:[:name,:id,:organization_id,:created_at,:updated_at] ,org_images_attributes: [:id,:organization_id,:caption, :photo_file_name, :photo_content_type,:photo_file_size,:photo_updated_at])
端 组织表格
<div class= "field">
<% if builder.object.new_record? %>
<p>
<%= builder.label :caption, "Image Caption" %>
<%= builder.text_field :caption %>
</p>
<p>
<%= builder.label :photo, "Image File" %>
<%= builder.file_field :photo %>
</p>
<% end %>
<% if builder.object.new_record? %>
<p>
<%= builder.label :name %>
<%= builder.text_field :name%>
</p>
<% end %>
<% end %>
Stringa和org_image模型
class OrgImage < ApplicationRecord
belongs_to :organization
has_attached_file :photo, :styles => { :small => "150x150>", :large => "320x240>" }
validates_attachment_presence :photo
validates_attachment_size :photo, :less_than => 5.megabytes
end
class Stringa < ApplicationRecord
belongs_to :organization
end
组织cotroller创建
def create
@organization = Organization.new(organization_params)
respond_to do |format|
if @organization.save
session[:organization_id]=@organization.id
format.html { redirect_to @organization, notice: 'Organization was successfully created.' }
format.json { render :show, status: :created, location: @organization }
else
format.html { render :new }
format.json { render json: @organization.errors, status: :unprocessable_entity }
end
end
端 git repository 感谢您的帮助