以下のような1対多の関係であるitemモデルとattachmentモデルを作りました。
これらを同一アクションで一括保存するためにaccepts_nested_attributes_forを利用しています。
viewのフォームから登録する際はattachmentモデルのvalidates :url, presence: trueがうまく動作するのですが、
以下のようなテストの場合、validates :url, presence: trueが動作せずにテストを通ってしまいます。
原因がわかる方、教えていただけないでしょうか?
よろしくお願いします。
Attachment.rb
# Table name `attachments` # Name | Type | Attributes # ----------------- | ------------------ | --------------------------- # **`id`** | `integer` | `not null, primary key` # **`item_id`** | `integer` | `not null` # **`url`** | `string(255)` | `not null` # **`created_at`** | `datetime` | `not null` # **`updated_at`** | `datetime` | `not null` class Attachment < ActiveRecord::Base validates :item, presence: true validates :url, presence: true #itemとattachmentは1対多 belongs_to :item, inverse_of: :attachments end
Item.rb
# Table name `items` # # Name | Type | Attributes # ----------------- | ------------------ | --------------------------- # **`id`** | `integer` | `not null, primary key` # **`title`** | `string(255)` | `not null` # **`content`** | `text(65535)` | # **`created_at`** | `datetime` | `not null` # **`updated_at`** | `datetime` | `not null` class Item < ActiveRecord::Base # titleは必須 validates :title, presence: true # itemとattachmentsは1対多 has_many :attachments, inverse_of: :item, dependent: :destroy accepts_nested_attributes_for :attachments end
items/new.html.slim
= form_for @item do |f| = f.label :title = f.text_field :title = f.label :content = f.text_field :content = f.fields_for :attachments do |c| = c.label :url = c.text_field :url = f.submit
items_controller.rb
def new @item = Item.new @item.attachments.build end def create @item = Item.new(item_params) if @item.save redirect_to( {action: :index}, notice: '投稿しました。' ) else render :new end end def item_params params.require(:item).permit(:title, :content, attachments_attributes: :url) end
items_controller_spec.rb
describe "#create" do it "create new item" do expect { post :create, item: { title: 'title', content: 'content' } }.to change { Item.count }.from(0).to(1) end end
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。