【问题标题】:Subscriber needs to follow List Owner but gets error订阅者需要关注列表所有者但出现错误
【发布时间】:2011-09-07 13:44:26
【问题描述】:

我有两种类型的用户,一种叫做list_owner,一种叫做subscriber。这些都是用设计制作的用户。订阅者应该能够关注 list_owner。我有另一个模型,称为关系来跟踪订阅者关注的对象。

我主要以http://ruby.railstutorial.org/ 为例。

这些是关系

class Relationship < ActiveRecord::Base

  attr_accessible :list_owner_id, :subscriber_id

  belongs_to :list_owner
  belongs_to :subscriber

end

class ListOwner < ActiveRecord::Base

  has_many :messages
  has_many :relationships, :dependent => :destroy, :foreign_key => "list_owner_id"

end

class Subscriber < ActiveRecord::Base

  has_many :relationships, :foreign_key => "subscriber_id",
                             :dependent => :destroy

 def follow!(list_owner)
      puts "-----------------------"

   relationships.create!(:subscriber_id => subscriber.id, :list_owner_id => list_owner.id)
 end

end

我与列表所有者一起制作了一个列表,其中包含订阅者可以订阅的按钮。

<%= form_for current_subscriber.relationships.build(:list_owner_id => l.id, :subscriber_id => @subscriber.id),
                 :remote => true do |f| %>
    <%= f.hidden_field :list_owner_id %>
    <%= f.hidden_field :subscriber_id %>
    <%= f.submit "Subscribe", :class => "button btn" %>
<% end %>



class RelationshipsController < ApplicationController
  def create
    puts "---------------------relationships CREATE---------------------"
    @list_owner = ListOwner.find(params[:relationship][:list_owner_id])
    current_subscriber.follow!(@list_owner)
        redirect_to root_path
  end

end

这是我得到的错误。我做错了什么?

Started POST "/relationships" for 127.0.0.1 at Wed Sep 07 15:37:17 +0200 2011
  Processing by RelationshipsController#create as JS
  Parameters: {"commit"=>"Subscribe", "relationship"=>{"list_owner_id"=>"2", "subscriber_id"=>"1"}, "authenticity_token"=>"m5plsJLdzuwNt1yKfDJFKD28GcR138V+pezbfbECCPk=", "utf8"=>"✓", "_"=>""}
  ListOwner Load (0.2ms)  SELECT "list_owners".* FROM "list_owners" WHERE "list_owners"."id" = 2 LIMIT 1
  Subscriber Load (0.2ms)  SELECT "subscribers".* FROM "subscribers" WHERE "subscribers"."id" = 1 LIMIT 1
Completed 500 Internal Server Error in 34ms

NameError (undefined local variable or method `subscriber' for #<Subscriber:0x102f140c0>):
  app/models/subscriber.rb:21:in `follow!'
  app/controllers/relationships_controller.rb:8:in `create'

【问题讨论】:

    标签: ruby-on-rails relationships


    【解决方案1】:

    没有定义这样的“订阅者”对象,但您不需要一个,因为您在关联集合上调用 create!() 方法,该方法将预先填充父对象。也就是调用subscriber.relationships.create!将设置subscriber_id =subscriber.id。

    def follow!(list_owner)
      relationships.create!(:list_owner_id => list_owner.id)
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-27
      • 1970-01-01
      • 2016-02-20
      • 2016-05-22
      • 1970-01-01
      • 2012-07-17
      • 2021-02-23
      • 2020-03-29
      相关资源
      最近更新 更多