LoginSignup
onaka0_0suita
@onaka0_0suita (m- yuto)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

【Rails6】deviseを使用しモデルを二つ作成し、どちらか片方のidを取得する方法

解決したいこと

Ruby on Railsでコミュニティサイトを制作しており、deviseを用いて、ユーザーモデルと店舗モデルの二つを使用しています。
コミュニティはどちらも作成出来るのですが、「ユーザーid」もしくは、「店舗id」のどちらかがあれば作成出来るようにしたいです。
解決策をご教授頂けますと幸いです。

該当するソースコード

▼データベース

class CreateCommunities < ActiveRecord::Migration[6.0]
  def change
    create_table :communities do |t|
      t.string     :community_title,   null: false
      t.text       :community_profile, null: false
      t.references :store,             null: false, foreign_key: true
      t.references :user,              null: false, foreign_key: true

      t.timestamps
    end
  end
end

▼モデル

community.rb
class Community < ApplicationRecord

  belongs_to :store
  belongs_to :user
  has_one_attached :image

  with_options presence: true do
    validates :community_title
  end
end

▼コントローラー

communities_controller.rb
class CommunitiesController < ApplicationController
  def index
    @communities = Community.page(params[:page]).per(1)
  end

  def new
    @community = Community.new
  end

  def create
    @community = Community.create(community_params)
    if @community.save
      redirect_to root_path
    else
      render :new
    end
  end

  private

  def community_params
    params.require(:community).permit(:community_title, :community_profile, :image).merge(user_id: current_user.id, store_id: current_store.id)
  end

end

▼ビュー(新規作成ページ)

new.html.rb
<%= render "shared/header" %>

<div id="community_new">
  <h2>コミュニティを作成</h2>
  <%= form_with(model: @community, local: true) do |f|%>

    <div class="community_new_field">
      <label>コミュニティ名<span>必須</span></label><br>
      <%= f.text_field :community_title %>
    </div>

    <div class="community_new_field">
      <label>プロフィール文<span>必須</span></label><br>
      <%= f.text_area :community_profile %>
    </div>

    <div class="community_new_field">
    <label>サムネイル画像<span>必須</span></label><br>
    <%= f.file_field :image, class: "community_img" %>
  </div>

  <div class="community_new_action">
    <%= f.submit "作成する" %>
  </div>

  <% end %>
</div>

<%= render "shared/footer" %>

自分で試したこと

NOT NULL制約を解除すると作成出来るようになると思うのですが、NOT NULL制約を解除せず作成出来る方法や何か良い案などありましたらご教授頂けますと幸いです。
よろしくお願いいたします。

0

1Answer

Comments

  1. @onaka0_0suita

    Questioner
    @getty104様
    ご回答下さりありがとうございます!
    初学者なもので、ポリモーフィック関連というテクニックは初めて聞きました。
    頂いた記事を拝見させて頂いたところ、行いたいことが実現出来そうでした!
    現在なかなか実現が出来なく後回しにしていましたので、記事を参考に開発してみたいと思います!
    ありがとうございます!

Your answer might help someone💌