Вопрос

Despite going through http://guides.rubyonrails.org/association_basics.html, I'm still having issues with a particular association in my rails app.

I have a user model, in which a user can either be a customer or a provider. I then allow customers to rate providers through a provider_rating model:

I currently have the following associations:

User.rb

has_many :customer_ratings, foreign_key: 'customer' 

Customer_rating.rb

belongs_to :user

What is the proper way to deal with associations where, in this case, a user both receives ratings and also gives ratings?

I thought has_and_belongs_to_many would make sense, but doesn't appear to be the case.

Это было полезно?

Решение 2

I ended up solving this without using Rolify. In my user table, I have a field this is user_type, which someone selects customer or provider. Once this customer/provider field was getting populated within the provider_rating form, I was able to keep the association:

has_many :customer_ratings, foreign_key: 'customer' 

When creating a rating for a customer, I used the following within my customer ratings controller:

  def create
    @user = User.find(params[:customer])
    @cust_rating = @user.customer_ratings.build(customer_rating_params)

    respond_to do |format|
      if @cust_rating.save
        format.html { redirect_to @user, notice: 'Thanks, your customer feedback has been recorded!' }
        format.json { render action: 'show', status: :created, location: @customer_rating }
      else
        format.html { render action: 'new' }
        format.json { render json: @customer_rating.errors, status: :unprocessable_entity }
      end
    end
  end

and access the provider details with

customer_rating.provider

Другие советы

First thing:

User.rb

has_many :customer_ratings, foreign_key: 'customer_id'

Second thing is that:

Provider and customer both are User so, you should use this gem

https://github.com/EppO/rolify to indetifying users roll.

And then you can store rating with user role to identify which user rate which userl.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top