簡體   English   中英

將has_many關聯的方法轉換為has_one關聯

[英]converting the methods for a has_many association to a has_one association

我有2個模型,用戶和common_apps。

用戶has_one:common_app。

在此之前,我以用戶has_many common_apps的身份編寫了代碼,但是我不確定如何為has_one關聯重寫代碼。 主要的困惑是如何在common_app控制器中構造“ new”。

嘗試時,出現未定義的方法錯誤。

undefined method `new' for #<CommonApp:>

這是我的代碼->

def new
    if current_user.common_app.any?
      redirect_to current_user
    else
        @common_app = current_user.common_app.new 
    end
  end

  def create 
    @common_app = current_user.common_app.build(common_app_params)
    if @common_app.save
        flash[:success] = "Common App Created!"
        redirect_to root_url
    else
        redirect_to 'common_apps/new'
    end
  end

  def show
    @common_apps = current_user.common_app
  end

如果這將是has_one關聯,您將如何重組它?

我想我知道應該如何“創建”->

      def create 
        @common_app = current_user.build_common_app(common_app_params)
        if @common_app.save
            flash[:success] = "Common App Created!"
            redirect_to root_url
        else
            redirect_to 'common_apps/new'
        end
      end

您的新操作應如下所示:

def new
  if current_user.common_app.present?
    redirect_to current_user
  else
    @common_app = current_user.build_common_app
  end
end

您也可以在不傳遞任何參數的情況下調用build_common_app ,這將為current_user初始化一個空的CommonApp。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM