0
林關聯模型和IM卡我有我的餐廳控制器關係模型軌道
before_action :set_restaurant, only: [:show, :edit, :update, :destroy]
def new
@restaurant = Restaurant.new
@restaurant.build_chef
end
def create
@restaurant = Restaurant.new(restaurant_params)
respond_to do |format|
if @restaurant.save
format.html { redirect_to @restaurant, notice: 'Restaurant was successfully created.' }
format.json { render action: 'show', status: :created, location: @restaurant }
else
format.html { render action: 'new' }
format.json { render json: @restaurant.errors, status: :unprocessable_entity }
end
end
end
def set_restaurant
@restaurant = Restaurant.find(params[:id])
end
def restaurant_params
params.require(:restaurant).permit(:avatar, :name, :description,
chef_attributes: [ :avatar, :name ]
)
end
這是我_form,即時通訊在create.html.erb渲染
<%= form_for(@restaurant, multipart: true) do |f| %>
<div class="field">
<%= f.label :restaurant_name %>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :description %>
<%= f.text_field :description %>
</div>
<div class="field">
<%= f.label :image %>
<%= f.file_field :avatar %>
</div>
<%= f.fields_for :chef do |f| %>
<div class="field">
<%= f.label :chef_name %>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :image %>
<%= f.file_field :avatar %>
</div>
<% end %>
<div class="actions">
<%= f.submit 'Add new restaurant' %>
<%= link_to 'Nevermind', restaurants_path, class: 'button' %>
</div>
<% end %>
那麼這是我的廚師模型
class Chef < ApplicationRecord
belongs_to :restaurant
validates :name, presence: true
validates :avatar,
attachment_content_type: { content_type: /\Aimage\/.*\Z/ },
attachment_size: { less_than: 5.megabytes }
has_attached_file :avatar, styles: {
thumb: '100x100>',
square: '200x200#',
medium: '300x300>'
}
end
,這是我的餐廳模型
class Restaurant < ApplicationRecord
has_one :chef
accepts_nested_attributes_for :chef
validates :name, presence: true
validates :avatar,
attachment_content_type: { content_type: /\Aimage\/.*\Z/ },
attachment_size: { less_than: 5.megabytes }
has_attached_file :avatar, styles: {
thumb: '100x100>',
square: '200x200#',
medium: '300x300>'
}
end
我的問題是,當我保存一個新的餐廳,沒有任何反應只是重新加載和留在窗體中,我不知道發生什麼我卡在這裏,可能它只是一個愚蠢的事情,但即時學習,謝謝支持。
這可能無法解決您的問題,但是您在'fields_for'塊中隱藏了'f'變量。你應該把它重命名爲'ff'或其他什麼東西,這樣就可以清楚'text_field'輸入被分配給'chef'參數。這可能會導致您的某些驗證失敗並重新加載表單。 – Shaun
完成了,但是你說得對,它沒有解決問題:/ – imjustaguy
當你提交表單時,你可以發佈developer.log文件顯示傳入參數的內容嗎?它應該是這樣的:'POST「/ url」for ...;參數:{「restaurant」=> {...},「chef」=> {...}}'。 – Shaun