如何将订户与事件相关联

时间:2018-05-02 09:11:19

标签: ruby-on-rails ruby

我试图将其作为订阅者,转到特定事件 每个示例使用以下URL:

http://localhost:3001/events/1/subscribers/new

但我不知道在创建新订阅者时如何关联event_id

目前我收到此错误:

Couldn't find Event with 'id'=

在路线中:

 resources :events do
    resources :subscribers #url/events/:events_id/subscribers/new
  end

  resources :events
  root 'events#index'
订阅者控制器中的

def show
  end

  # GET /subscribers/new
  def new
    #puts "Look for me in console\n"
    #puts params.inspect
    @event = Event.find(params[:events_id])
    @subscriber = @event.Subscriber.new
  end

  # GET /subscribers/1/edit
  def edit
  end

  # POST /subscribers
  # POST /subscribers.json
  def create
    @event = Event.find(params[:order_id])
    @subscriber = @event.Subscriber.new order_params
    #@subscriber = Subscriber.new(subscriber_params)

    respond_to do |format|
      if @subscriber.save
        SubsMailer.new_subscriber(@subscriber).deliver
        format.html { redirect_to @subscriber, notice: 'Subscriber was successfully created.' }
        format.json { render :show, status: :created, location: @subscriber }
      else
        format.html { render :new }
        format.json { render json: @subscriber.errors, status: :unprocessable_entity }
      end
    end
  end
在new.html.erb中:

<h1>New Subscriber</h1>

<%= render 'form', subscriber: @subscriber %>

<%= link_to 'Back', subscribers_path %>

模特协会:

event.rb:

class Event < ApplicationRecord
  has_many :subscribers, dependent: :destroy
end

subscriber.rb:

class Subscriber < ApplicationRecord
  belongs_to :event
  validates :email, presence: true,
                    format: /\A\S+@\S+\z/,
                    uniqueness: { case_sensitive: false }
end

2 个答案:

答案 0 :(得分:4)

嗯,我认为documentation会帮助您了解您需要做什么。

如果一开始就需要更改模型。对于Event,你可以有很多对很多 - &gt;订户协会或一对多。一对多是最简单的显示,因此您需要将其添加到您的订阅者模型:

belongs_to :event

这是你的活动模特:

has_many :subscribers

添加新迁移:

def change
  remove_column :subscribers, :events_id
  remove_column :subscribers, 'Event_id'
  add_column :subscribers, :event_id, :integer
end

然后在您的控制器中,您应该更改方法调用,因为Subscriber是一个类,而不是方法。

def new
  @event = Event.find(params[:event_id])
  @subscriber = @event.subscribers.build
end

你应该确保在你的数据库中你有这个id的事件。 要检查它,您可以尝试调试控制器代码:

def new
  puts "Event ids: " + Event.all.map(&:id).inspect
  @event = Event.find(params[:event_id])
  @subscriber = @event.subscribers.build
end

在您的日志中,您应该具有以下内容:

Event ids: [1]

答案 1 :(得分:1)

我认为你的params[:eventS_id]方法中只有一个拼写错误。如果params[:event_id]event.subscribers.new,请致电def new #puts "Look for me in console\n" #puts params.inspect @event = Event.find(params[:event_id]) @subscriber = @event.subscribers.build end 。您也没有正确引用您的关联。它应该是def up change_table :subscribers do |t| t.remove :Event_id t.references :event end end def down change_table :subscribers do |t| t.remove :event_id t.add :Event_id, :integer end end

{{1}}

迁移:

{{1}}

请告诉我这是否有帮助,如果您有任何其他问题