2

以下是型号:

class User < ActiveRecord::Base
   has_many :companies_users
   has_many :companies, :through => :companies_users
end

class Company < ActiveRecord::Base
   has_many :companies_users
   has_many :users, :through => :companies_users

   accepts_nested_attributes_for :users
   attr_accessible :name, :address_1, :address_2, :area, :city, :state, :zipcode, :country, :users_attributes

   after_create :create_subscriptions

   def create_subscriptions
     subscription=Subscription.create(:company_id => self.id, :subscription_dt => Date.today, :is_active => 'Y', :user_id => self.users.first.id)
     subscription.save
   end      

end

class CompaniesUser < ActiveRecord::Base
    belongs_to :user
    belongs_to :company 
end

以下是spec/factories/factory.rb

FactoryGirl.define do

  factory :company do |f|
    f.name "TestCompany"
    f.domain_url "test_url"
    users {|t| [t.association(:user)] } 
  end

  factory :user do |f| 
    f.first_name "John"
    f.last_name "Doe"
    f.password  "password"
    f.email "JohnDoe@test.com"
    f.mobile_no "25589875"
    f.fax_no  "25548789"
    f.office_no  "25578455"     
  end

  factory :companiesuser do |f|
    association :user
    association :company
  end

end

以下是我的规范/模型/company_spec.rb

 context "Check methods" do

    it "check after create methods" do     
      company = FactoryGirl.create(:company)
    end

  end

在执行上面的 company_spec 时,由于公司模型中存在方法订阅并在创建回调 create_subscriptions.which 需要 self.users.first.id 后调用,它会产生一个问题,它没有得到它并为我提供以下错误。

$ rspec spec/models/company_spec.rb 
F

Failures:

  1) Company Model: Check methods check after create methods
     Failure/Error: company = FactoryGirl.create(:company)
     RuntimeError:
       Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
     # ./app/models/company.rb:47:in `create_subscriptions'
     # ./spec/models/company_spec.rb:45:in `block (3 levels) in <top (required)>'

谁能让我知道我需要做什么或任何与协会相关的问题?它会产生问题,因为它首先在公司中输入值,但无法在用户表中输入值,因此无法获取订阅方法中所需的用户 ID。

4

2 回答 2

1

我通过更改“spec/model/company_spec.rb”中的代码解决了上述问题,如下所示:

context "Check methods" do    
    it "check after create methods" do
      company = create(:company,"name"=>"mycom","domain_url"=>"test","users_attributes"=>{"0"=>{"email"=>"test@testing.com","password"=>"password","password_confirmation"=>"password"}})
    end
  end

它也在我的连接表中创建了数据并成功运行。显然它不是由工厂加入完成的。我这里直接传用户属性。所以删除线

users {|t| [t.association(:user)] }

从公司的工厂。

于 2013-10-16T06:58:37.697 回答
0

我已经做了一个嵌套的 has_many :through ,你必须基本上将属性传递给 :companies_users 模型,然后传递给 :users 模型


我的代码(Rails 4.0)

形式

#views/admin/posts/new
<%= form_for [:admin, resource], :html => { :multipart => true }  do |f| %>
    <table class="resource_table">
        <thead>
            <th colspan="2"><%= params[:action].capitalize %> <%= resource_class %></th>
        </thead>
        <tbody class="form">
            <% attributes.each do |attr| %>
                <tr class="<%= cycle('odd', '')%>">
                    <td><%= resource_class.human_attribute_name(attr) %></td>
                    <td>
                        <% if attr == "body" %>
                            <%= f.text_area attr, :rows => 60, :cols => 80, :class => "redactor" %>
                        <% else %>
                            <%= f.text_field attr, :value => resource.public_send(attr).to_s %>
                        <% end %>
                    </td>
                </tr>
            <% end %>
            <%= f.fields_for :images_posts do |images_posts| %>
                <%= images_posts.fields_for :image do |images| %>
                    <tr>
                        <td>Image</td>
                        <td><%= images.file_field :image %></td>
                    </tr>
                <% end %>
                <tr>
                    <td>Caption</td>
                    <td><%= images_posts.text_field :caption %></td>
                </tr>
            <% end %>
            <tr class="dull">
                <td colspan="2"><%= f.submit "Go" %></td>
            </tr>
        </tbody>
    </table>
<% end %>

楷模

#models/image_post.rb (the join model)   
class ImagePost < ActiveRecord::Base
        
        #Associations
        belongs_to :post, :class_name => 'Post'
        belongs_to :image, :class_name => 'Image'
        
        #Validations
        validates_uniqueness_of  :post_id, :scope => :image_id
        
        #Nested Association (Can upload & add images from form)
        accepts_nested_attributes_for :image, :allow_destroy => true
        
end


#models/image.rb
class Image < ActiveRecord::Base

    #Associations
    has_many :products, :class_name => 'Product', :through => :images_products, dependent: :destroy
    has_many :images_products, :class_name => 'ImageProduct'

    has_many :posts, :class_name => 'Post', :through => :images_posts, dependent: :destroy
    has_many :images_posts, :class_name => 'ImagePost'

    has_many :brands, :class_name => 'Brand', :through => :brands_images, dependent: :destroy
    has_many :brands_images, :class_name => 'BrandImages'

    #Image Upload 
    Paperclip.options[:command_path] = 'C:\RailsInstaller\ImageMagick'
    has_attached_file :image,
        :styles => { :medium => "x300", :thumb => "x100" },
        :default_url => "",
        :storage => :s3,
        :bucket => ''
        :s3_credentials => S3_CREDENTIALS

    #Validations
    validates_presence_of :image, :message => "No Image Present!"

end

#models/post.rb
class Post < ActiveRecord::Base

    #Images
    has_many :images, -> { uniq }, :class_name => 'Image', :through => :images_posts, dependent: :destroy
    has_many :images_posts, :class_name => 'ImagePost'

    #Nested Association (Can upload & add images from form)
    accepts_nested_attributes_for :images_posts, :allow_destroy => true

end

这对我来说是一个很大的帮助:Rails nested form with has_many :through, how to edit attributes of join model?


诊断您的问题

我发布了我的代码,为您提供了一个可行的示例,说明您可以做什么(我的仍然需要改进,但它可以工作)

查看您的代码,您应该将“accepts_nested_attributes_for”添加到您的 Companies_users.rb 模型中,如下所示:

accepts_nested_attributes_for :user

在您的公司模型中,将您的accepts_nested_attributes_for 更改为:

accepts_nested_attributes_for :companies_users
于 2013-10-11T06:41:40.333 回答