ruby-on-rails - 如何将订阅者关联到事件

标签 ruby-on-rails ruby

我正在尝试使它成为某个事件的订阅者 每个示例使用以下网址:

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

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

目前我收到这个错误:

Couldn't find Event with 'id'=

在 route :

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

  resources :events
  root 'events#index'

在订阅者 Controller 中:

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

模型关联:

事件.rb:

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

订阅者.rb:

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

最佳答案

嗯,我觉得这documentation将帮助您了解您需要做什么。

如果一开始您需要短暂地更改您的模型。对于 Event -> Subscriber 关联,您可以拥有多对多或一对多。一对多是最简单的显示方式,因此您需要将其添加到订阅者模型中:

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

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

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

并且您应该确保在您的数据库中有具有此 ID 的事件。 要检查它,您可以尝试调试您的 Controller 代码:

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

在你的日志中你应该有这样的东西:

Event ids: [1]

关于ruby-on-rails - 如何将订阅者关联到事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50130964/

相关文章:

ruby-on-rails - 充电失败时检索 Stripe 充电 ID

ruby-on-rails - 如何让 rvm 在 capistrano 部署时创建我的 gemset?

ruby-on-rails - 在 postgres 中按升序排序,最后为 0

ruby-on-rails - 对 Rails 中的嵌套资源和身份验证感到困惑

arrays - 合并两个不相等的数组进行散列

ruby - 分配实例变量的快捷方式

ruby-on-rails - Lift 框架是 "easy"还是 Ruby on Rails 或 Django?

ruby-on-rails - Heroku CI 与 rails 固定装置

mysql - 由于对 schema_migrations 的唯一约束,Rails 单元测试失败

ruby-on-rails - 如何在 Ruby 中动态创建具有给定方法和方法体的类?