簡體   English   中英

控制器中的 Rails has_many 關聯問題

[英]Rails has_many association issue in controller

我有一個用該設計設計的公司模型,當公司登錄時,公司可以創建事件,以便公司有許多事件,並且事件屬於公司,事件控制器給出為

class EventsController < ApplicationController
  before_action :company_signed_in?
  def index
    @events = Event.all
  end

  def new
    @event = current_company.events.build
  end

  def create
    @event = current_company.events.build(event_params)
    if @event.save
      flash[:success] = "Profile saved"
      redirect_to company_events_path(current_company)
    else
      flash[:error] = "Error"
      render :new
    end
  end

  def show
    @event = current_company.events.where(id: params[:id]).first
  end

  private

  def event_params
    params.require(:event).permit(:name, :company_id, :category_id, :event_date, :event_info, :place, :event_avatar)
  end

end

並且公司模式有

has_many :events

並且事件模型有

belongs_to :company

事件的新觀點有

   <%= form_for [current_company, @event] do |f| %>
 <%= f.text_field :name %>
    <% end %>

並且節目視圖有

<%= @event.name %>

我的路線是

resources :companies do
    resource :company_profile, :events
  end

現在我想要做的是當前公司可以創建一個事件,當創建事件時,它應該被重定向到剛剛產生的事件的顯示頁面

我需要創建一個事件,以便我可以獲取諸如companies/3/events/3這種類型的 URL

問題是當我去表演動作時,我得到了未定義的方法“名稱”,請幫忙! 在日志中我有

Started GET "/companies/3/events" for 127.0.0.1 at 2015-07-30 16:41:54 +0530
Processing by EventsController#show as HTML
  Parameters: {"company_id"=>"3"}
  Company Load (0.3ms)  SELECT  `companies`.* FROM `companies` WHERE `companies`.`id` = 3  ORDER BY `companies`.`id` ASC LIMIT 1
  CompanyProfile Load (0.3ms)  SELECT  `company_profiles`.* FROM `company_profiles` WHERE `company_profiles`.`company_id` = 3 LIMIT 1
  Event Load (0.3ms)  SELECT  `events`.* FROM `events` WHERE `events`.`company_id` = 3 AND `events`.`id` IS NULL  ORDER BY `events`.`id` ASC LIMIT 1
  Rendered events/show.html.erb within layouts/application (12.5ms)
Completed 500 Internal Server Error in 32ms (ActiveRecord: 0.8ms)

ActionView::Template::Error (undefined method `name' for nil:NilClass):
    1: 
    2: <label>Name : </label>
    3: <%= @event.name %>
    4: <%= @event.event_date %></br></br>
    5: <label>Age : </label>
    6: <%= @event.place %></br></br>
  app/views/events/show.html.erb:3:in `_app_views_events_show_html_erb__541678279__634038278'

您應該嘗試以下方法,看看它是否有效:

def show
@event = Event.find(params[:id])
end

您沒有將事件的 id 傳遞給 show 操作。 如參數所示,僅傳遞 company_id

   Parameters: {"company_id"=>"3"}

所以當它在 id NULL的事件中查詢時,它沒有找到任何事件,因此null.name崩潰了

要么將事件的id傳遞給 show 動作。 或者為了測試你應該這樣做

def show
  @event = current_company.events.first
end

暫無
暫無

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

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