我是 ruby on rails 和一般编码的新手。我写了一个嵌套的 form_for,其中 Price 类属于 Item 类。:amount、:timeframe 和 :item_id 值将通过控制器存储。操作结束后,仅存储 :timeframe 和 :item_id 而不是 :amount 值。
这是否与:
嵌套形式?
:amount? 的数据类型和/或精度和比例详细信息?
我的控制器方法也可能有问题吗?
任何澄清将不胜感激!
这是表格:
<%= form_for @item, html: {multipart: true} do |f| %>
<div class="main-form">
<div class="new-item-form">
<%= f.label :title %>
<%= f.text_field :title %>
</div>
<div class="new-item-form">
<%= f.label :description %>
<%= f.text_field :description %>
</div>
<div class="new-item-form">
<%= f.label :deposit %>
<%= f.text_field :deposit %>
</div>
<div class="new-item-form">
<%= f.label :tags %>
<%= f.text_field :tags %>
</div>
<div class="new-item-form">
<%= f.label :image %>
<%= f.file_field :image %>
</div>
<%= fields_for :price do |f| %>
<div class="new-item-form">
<%=f.label :timeframe %>
<%= select_tag(:timeframe, options_for_select([["Hour"],["Day"],["Week"]])) %>
</div>
<div class="new-item-form">
<%=f.label :amount %>
<%=f.number_field :amount %>
</div>
<% end %>
<%= f.submit %>
<%end%>
这是控制器:
class ItemsController < ApplicationController
def show
@item = Item.find(params[:id])
@price = Price.where(item_id: @item.id).first
end
def new
@item = Item.new
end
def create
@item = Item.new(item_params)
if @item.save
@price = Price.create(:timeframe => params[:timeframe], :amount => params[:amount], :item_id => @item.id)
@price.save
redirect_to @item, notice: "Item Successfully Added!"
else
flash[:message] = "Something did not validate"
render 'new'
end
end
private
def item_params
params.require(:item).permit(:title, :description, :image, :user_id, :deposit, :tags)
end
end
其他文档包括 Item 模型和 Price 模型:
class Item < ActiveRecord::Base
validates :title, :description, :deposit, :tags, presence: true
belongs_to :user
has_many :prices, :dependent => :destroy
has_many :reviews, :dependent => :destroy
has_many :ratings, :dependent => :destroy
has_many :users_that_reviewed_this, through: :reviews, source: :user
has_many :users_that_rated_this, through: :ratings, source: :user
end
class Price < ActiveRecord::Base
belongs_to :item end
以及这些类的数据库模式:
create_table "items", force: :cascade do |t|
t.string "title"
t.string "description"
t.string "image"
t.integer "user_id"
t.integer "deposit"
t.string "type"
t.string "tags"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "prices", force: :cascade do |t|
t.string "timeframe"
t.decimal "amount"
t.integer "item_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end