I have quite a complicated setup of associations to allow my model :thing to be rated, which I think can be best understood by looking at my models. Basically, when a new :thing is created, new :thing_ratings are also created based on the :ratings that belong to the :categories that the :thing belongs to.
For example, if a :category “Books” has a :rating “Plot”, then a new :thing that is created with an association to Books should have a :thing_rating also named “Plot”.
The problem is, though the :thing and :thing_ratings are created without problems, on the :thing show page, I'm getting this error:
ActiveRecord::HasManyThroughNestedAssociationsAreReadonly in ThingsController#show
Cannot modify association 'Thing#thing_ratings' because it goes through more than one other association.
How can I get around this problem? I saw an answer to a similar problem that suggested to make the association between :thing and :thing_rating readonly, but I also want to be able to create instances of another model :up_votes for :thing_ratings, and I don't think I can do that if the association is readonly.
models/thing.rb
has_many :category_things
has_many :categories, :through => :category_things
has_many :category_ratings, through: :categories
has_many :ratings, :through => :categories
has_many :thing_ratings, through: :ratings
models/category.rb
has_many :category_ratings
has_many :ratings, :through => :category_ratings
has_many :category_things
has_many :things, :through => :category_things
models/rating.rb
has_many :category_ratings
has_many :categories, :through => :category_ratings
has_many :thing_ratings
has_many :things, :through => :thing_ratings
models/category_thing.rb
belongs_to :category
belongs_to :thing
models/category_rating.rb
belongs_to :category
belongs_to :rating
models/thing_rating.rb
belongs_to :rating
belongs_to :thing
has_many :up_votes, as: :voteable
controllers/things_controller.rb
def show
#thing = Thing.find(params[:id])
#thing.categories.build
#category_thing = CategoryThing.all
#category_rating = CategoryRating.all
#thing_ratings = #thing.category_ratings
#thingcats = #thing.categories
#thing.thing_ratings.build
# ...
end
def create
#thing = Thing.new(thing_params)
#category = Category.all
#thing.categories.build
#thing_ratings = #thing.category_ratings
#thingcats = #thing.categories
#thingrats = #thing.ratings
if #thing.save
params["categories"].strip.split(',').map(&:strip).each do |name|
CategoryThing.create!(category_id: Category.where(name: name).first.id, thing_id: #thing.id)
end
#thingrats.each do |r|
ThingRating.create!(rating_id: r.id, thing_id: #thing.id, name: r.name)
end
redirect_to new_thing_path
end
end
Well it turns out that I didn't actually have to associate thing_ratings with ratings at all. I just made thing_ratings belong directly to things.
Related
I have a model with associations. How to create/update the associations as CRUD operations are performed on the model.
That is, when I run
#v1_seller = V1::Seller.new(seller_params)
#v1_seller.save
It should save the associations.
Should I create after_create hooks and pass the params (but then I will have to do the same in update)? Or am I missing something? I feel that it should be done automatically in rails.
currently I am doing it explicitly:
#v1_seller = V1::Seller.new(seller_params)
if #v1_seller.save
#v1_seller.assign_categories(params)
my seller model:
class V1::Seller < ActiveRecord::Base
has_many :categories, :class_name => 'V1::Category', dependent: :delete_all
has_many :category_names, :class_name => 'V1::CategoryName', through: :categories
# right now I am manually calling this after a create/update operation in my controller
def assign_categories(params)
params.require(:seller).require(:categories)
params.require(:seller).permit(:categories => []).permit(:name, :brands => [])
self.categories.clear
params[:seller][:categories].each do |c|
if c[:brands].nil? || c[:brands].empty?
next # skip the category if it has no brands associated with it
end
category_name = c[:name]
category = V1::Category.new
category.category_name = V1::CategoryName.find_by(name: category_name)
category.seller = self
category.save
c[:brands].each do |b|
begin
category.brand_names << V1::BrandName.find_by(name: b)
rescue ActiveRecord::RecordInvalid
# skip it. May happen if brand is already added to the particular category
end
end
end
end
end
And V1::Cateogry model:
class V1::Category < ActiveRecord::Base
belongs_to :category_name, :class_name => 'V1::CategoryName', inverse_of: :category
belongs_to :seller, :class_name => 'V1::Seller', inverse_of: :category
has_many :brands, :class_name => 'V1::Brand', dependent: :delete_all, inverse_of: :category
has_many :brand_names, :class_name => 'V1::BrandName', through: :brands, inverse_of: :category
validates :seller, :uniqueness => {:scope => [:category_name, :seller]}
end
Seem like you need nested attributes.
Checkout the docs here: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
I basically followed the ROR guide, http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association, to create the relationship models as shown below.
Because of the through association, I figured that #user.trips would give you both the trips that the user created and the trips that belong to the user. However, when I do #user.trips.count in console, the result was only the number of trips that the users created; the trips that belonged to the user through the 'group' association was not counted.
Question: How do I get my view to display both the trips that the user created and the trips that the user belongs to through 'group'?
user/show.html.erb
<% unless #user.all_trips.empty? %>
<% #user.all_trips.each do |trip| %>
<!-- Content -->
<% end %>
<% end %>
user.rb
class User < ActiveRecord::Base
has_many :group_trips, :through => :groups,
:source => :trip
has_many :trips, :dependent => :destroy
has_many :groups
def all_trips
self.trips | self.group_trips
end
end
trip.rb
class Trip < ActiveRecord::Base
belongs_to :user
belongs_to :traveldeal
has_many :groups
has_many :users, :through => :groups
end
group.rb
class Group < ActiveRecord::Base
belongs_to :trip
belongs_to :user
end
Thanks!
Edit: Modified code per TSherif's partial solution.
Edit 2: Fixed up the all_trips method. Everything appears to work for me at this point.
Oh! I think I get what you're trying to do and why it's a problem. I was wondering why has_many :trips was called twice. But from what I understand, you have two different User-Trip relationships. These two can't have the same name, otherwise one will hide the other. Try something like this:
class User < ActiveRecord::Base
has_many :group_trips, :through => :groups,
:class_name => "Trip"
has_many :trips, :dependent => :destroy
has_many :groups
def all_trips
Trip.joins(:groups).where({:user_id => self.id} | {:groups => {:user_id => self.id}})
end
end
Or if you're using an older version of Rails that doesn't have MetaWhere:
def all_trips
Trip.joins(:groups).where("(trips.user_id = ?) OR (groups.user_id = ?)", self.id, self.id)
end
i have three models, all for a has_many :through relationship. They look like this:
class Company < ActiveRecord::Base
has_many :company_users, dependent: :destroy
has_many :users, through: :company_users
accepts_nested_attributes_for :company_users, :users
end
class CompanyUser < ActiveRecord::Base
self.table_name = :companies_users #this is because this was originally a habtm relationship
belongs_to :company
belongs_to :user
end
class User < ActiveRecord::Base
# this is a devise model, if that matters
has_many :company_users, dependent: :destroy
has_many :companies, through: :company_users
accepts_nested_attributes_for :company_users, :companies
end
this loads fine, and the joins are built fine for queries. However, whenever i do something like
#company = Company.last
#user = #company.users.build(params[:user])
#user.save #=> true
#company.save #=> true
both the User record and the CompanyUser records get created, but the company_id field in the CompanyUser record is set to NULL
INSERT INTO `companies_users` (`company_id`, `created_at`,`updated_at`, `user_id`)
VALUES (NULL, '2012-02-19 02:09:04', '2012-02-19 02:09:04', 18)
it does the same thing when you #company.users << #user
I'm sure that I'm doing something stupid here, I just don't know what.
You can't use a has_many :through like that, you have to do it like this:
#company = Company.last
#user = User.create( params[:user] )
#company.company_users.create( :user_id => #user.id )
Then you will have the association defined correctly.
update
In the case of the comment below, as you already have accepts_nested_attributes_for, your parameters would have to come like this:
{ :company =>
{ :company_users_attributes =>
[
{ :company_id => 1, :user_id => 1 } ,
{ :company_id => 1, :user_id => 2 },
{ :company_id => 1, :user_id => 3 }
]
}
}
And you would have users being added to companies automatically for you.
If you have a has_many :through association and you want to save an association using build you can accomplish this using the :inverse_of option on the belongs_to association in the Join Model
Here's a modified example from the rails docs where tags has a has_many :through association with posts and the developer is attempting to save tags through the join model (PostTag) using the build method:
#post = Post.first
#tag = #post.tags.build name: "ruby"
#tag.save
The common expectation is that the last line should save the "through" record in the join table (post_tags). However, this will not work by default. This will only work if the :inverse_of is set:
class PostTag < ActiveRecord::Base
belongs_to :post
belongs_to :tag, inverse_of: :post_tags # add inverse_of option
end
class Post < ActiveRecord::Base
has_many :post_tags
has_many :tags, through: :post_tags
end
class Tag < ActiveRecord::Base
has_many :post_tags
has_many :posts, through: :post_tags
end
So for the question above, setting the :inverse_of option on the belongs_to :user association in the Join Model (CompanyUser) like this:
class CompanyUser < ActiveRecord::Base
belongs_to :company
belongs_to :user, inverse_of: :company_users
end
will result in the following code correctly creating a record in the join table (company_users)
company = Company.first
company.users.build(name: "James")
company.save
Source: here & here
I suspect your params[:user] parameter, otherwise your code seems clean. We can use build method with 1..n and n..n associations too, see here.
I suggest you to first make sure that your model associations works fine, for that open the console and try the following,
> company = Company.last
=> #<Tcompany id: 1....>
> company.users
=> []
> company.users.build(:name => "Jake")
=> > #<User id: nil, name: "Jake">
> company.save
=> true
Now if the records are being saved fine, debug the parameters you pass to build method.
Happy debugging :)
I'm a beginner and it's hard to explain my problem:
My models:
class Skill
has_many :categories
has_many :positions, :through => :categories
end
class Category
belongs_to :skill
has_many :positions
end
class Position
belongs_to :category
has_one :skill, :through => :category
end
I can successfully eager load everything, like this:
#skills = Skill.includes(:positions)
However sometimes I want to apply a scope on the Positions:
class Position
...
scope :active, where(:hidden => false)
end
I wish I could do:
#skills = Skill.includes(:positions.active)
Instead, I apply the scope in the views, but the eager loading doesn't work anymore:
<%= skill.positions.acitve ... %>
Is it possible to have both eager loading and scope?
You could use another association:
class Skill
has_many :categories
has_many :positions, :through => :categories
has_many :active_positions, :through => :categories
end
class Category
belongs_to :skill
has_many :positions
has_many :active_positions, :class_name => "Position", :conditions => {:hidden => false}
end
class Position
belongs_to :category
has_one :skill, :through => :category
end
And then
#skills = Skill.includes(:active_positions)
But then you'll get two associations. If you ever use skill.positions, all the skill's positions will be loaded from the database. You should only use skill.active_positions.
Try this:
#skills = Skill.includes(:positions).where('position.active = TRUE')
In my form for member_profile, I would like to have role checkboxes that are visible for admins. I would like to used some nested form_for, but can't make it work, so I've resorted to manually creating the check_box_tags (see below), and then manually adding them to member_profile.member.
Note that the Member model is Devise, and I don't want to mix those fields in with my MemberProfile data, in case I change auth systems in the future.
class Member < ActiveRecord::Base
has_one :member_profile
has_many :member_roles
has_many :roles, :through => :member_roles
end
class MemberProfile < ActiveRecord::Base
belongs_to :member
has_many :member_roles, :through => :member
#has_many :roles, :through => :member_roles #can't make this work work
end
class Role < ActiveRecord::Base
has_many :member_roles
validates_presence_of :name
end
class MemberRole < ActiveRecord::Base
belongs_to :member
belongs_to :role
end
Form (haml)
= form_section do
- Role.all.each do |x|
=check_box_tag 'member[role_ids][]',
x.id,
begin #resource.member.role_ids.include?(x.id) rescue nil end
=x.name
member_profiles_controller.rb
def update
if #resource.update_attributes params[:member_profile]
#resource.member.role_ids = params[:member][:role_ids]
redirect_to(#resource, :notice => 'Member profile was successfully updated.')
else
render :action => "edit"
end
end
I've decided it only makes sense to do a nested has_many :through on Update, since the join model is what is being 'gone through' to get to the has_many :through model. Before the hmt is created, there is obviously no record in the join model.