我正在尝试以嵌套的形式验证:picture
模型上user_items
的存在。
item.rb的
validates :name, presence: true, uniqueness: true
validates :description, presence: true
has_many :user_items, inverse_of: :item
has_many :users, -> { uniq }, through: :user_items
belongs_to :user
accepts_nested_attributes_for :user_items
validates_associated :user_items
user_item.rb
belongs_to :user
belongs_to :item, inverse_of: :user_items
mount_uploader :picture, PictureUploader
validates :picture, presence: true
validate :picture_size
items_controller.rb
def new
@item = Item.new
@item.user_items.build
end
def create
@item = item.new item_params
if @item.save
redirect_to items_path, notice: "Thank you for your item request!"
else
render :new
end
end
private
def item_params
params.require(:item).permit(:name, :description, :tag_list, user_items_attributes: [:picture]).merge(created_by: current_user.id)
end
new.html.erb
<%= simple_form_for @item, html: { class: "create-item-form" } do |item_builder| %>
<div class="well">
<%= item_builder.input :name, required: false, error: false, label: "Item name" %>
<%= item_builder.input :description, as: :text, required: false, error: false, label: "Description of item" %>
<%= item_builder.input :tag_list, required: false, label: "Tags (these will help users find your item)" %>
<%= item_builder.simple_fields_for :user_items do |user_item_builder| %>
<%= user_item_builder.input :picture, as: :file, required: false, label: "Picture of you with this item" %>
<% end %>
</div>
<div class="clearfix">
<%= item_builder.submit 'Submit new item request', class: "btn btn-primary pull-right inherit-width" %>
</div>
<% end %>
这不起作用。我提交了一份空白表格,只有名称和说明验证触发。
更新
奇怪的是,如果我在user_id的表单中添加一个hidden_field,验证将会起作用:
<%= user_item_builder.input :user_id, as: :hidden, input_html: { value: current_user.id } %>
这里发生了什么?
UPDATE2:
如果我更改了创建操作,验证似乎也有效:
def create
@item = item.new item_params
@item.user_items.build
if @item.save
redirect_to items_path, notice: "Thank you for your item request!"
else
render :new
end
end
为什么我需要添加@item.user_items.build
?这样做的正确方法是什么?