控制器

时间:2015-07-30 11:04:38

标签: ruby-on-rails devise associations has-many

我有一个公司模型设计与设计,当公司登录时公司可以创建事件,以便公司有许多事件和事件属于公司事件控制器给出

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 %>

并且show view有

<%= @event.name %>

我的路线是

resources :companies do
    resource :company_profile, :events
  end

现在我想要做的是当前公司可以创建一个事件,当事件创建时,它应该被重定向到刚刚生成的事件的显示页面

我需要创建一个事件,以便我可以像companies/3/events/3这样的网址获取网址

问题是,当我要参加演出动作时,我会得到未定义的方法&#39; name&#39;请帮忙 !在日志中我有

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'

2 个答案:

答案 0 :(得分:0)

试试这个:

def show

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

答案 1 :(得分:0)

您没有将事件ID传递给show动作。只传递company_id,如参数

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

所以当它在id为NULL的事件中进行查询时,它没有找到任何事件,因此null.name正在崩溃

id事件传递给show动作。或测试你应该这样做

def show
  @event = current_company.events.first
end