has_many :through breaks upon find_or_initialize_by - ruby-on-rails

I have a model, Feed, that has and belongs to many FilteredUsers. In this case I have implemented it through a has_many :through relationship.
class Feed < ActiveRecord::Base
has_many :denials, :dependent => :destroy
has_many :filtered_users, :through => :denials
I would like to create a record if it doesn't exist or find the object if it does exist. When I try and use the find_or_initialize_by (or find_or_create_by) an exception is thrown saying undefined method 'feed_id=' for <FilteredUser..
Here is the code:
feed = Feed.find(params[:id])
user = feed.filtered_users.find_or_initialize_by_user_url(params[:user_url])
if params[:status] == "block"
feed.filtered_users << user
else
feed.filtered_users.delete(user)
end
feed.save
Any suggestions on how to fix this or how to work around it DRYly?
Thanks!

First, because it's a has_many :through relationship, the initialization has no way of knowing which denial the new filtered_user should be associated with. If you want to use find_or_initialize_by, you need to run it on a specific denial that is associated with the feed.
Build a new filtered_user and associate it with a specific denial.
Second, agreeing with ErsatzRyan, the general logic seems a bit off.

Wouldn't it be easier to check the params[:status] first and then do what you need to do?
feed = Feed.find(params[:id])
if params[:status] == 'block'
feed.filtered_users.build(:user_url => params[:user_url])
else
feed.filtered_users.find_by_user_url(params[:user_url]).delete
end
feed.save
warning this is air coded not tested

Related

Error in custom uniqueness validation for rspec

I am trying to create a rspec test for custom validation in a spree extension(like a gem)
I need to validate uniqueness of a variants
option values for a product (all Spree models)
Here is the basic structure of models(Although they are part of spree, a rails based e-commerce building):
class Product
has_many :variants
has_many :option_values, through: :variants #defined in the spree extension, not in actual spree core
has_many :product_option_types
has_many :option_types, through: :product_option_types
end
class Variant
belongs_to :product, touch: true
has_many :option_values_variants
has_many :option_values, through: option_values
end
class OptionType
has_many :option_values
has_many :product_option_types
has_many :products, through: :product_option_types
end
class OptionValue
belongs_to :option_type
has_many :option_value_variants
has_many :variants, through: :option_value_variants
end
So I have created a custom validation to check the uniqueness of a variants option values for a certain product. That is a product(lets say product1) can have many variants. And a variant with option values lets say (Red(Option_type: Color) and Circle(Option_type: Shape)) have to unique for this product
Anyway this is the custom validator
validate :uniqueness_of_option_values
def uniqueness_of_option_values
#The problem is in product.variants, When I use it the product.variants collection is returning be empty. And I don't get why.
product.variants.each do |v|
#This part inside the each block doesn't matter though for here.
variant_option_values = v.option_values.ids
this_option_values = option_values.collect(&:id)
matches_with_another_variant = (variant_option_values.length == this_option_values.length) && (variant_option_values - this_option_values).empty?
if !option_values.empty? && !(persisted? && v.id == id) && matches_with_another_variant
errors.add(:base, :already_created)
end
end
end
And finally here are the specs
require 'spec_helper'
describe Spree::Variant do
let(:product) { FactoryBot.create(:product) }
let(:variant1) { FactoryBot.create(:variant, product: product) }
describe "#option_values" do
context "on create" do
before do
#variant2 = FactoryBot.create(:variant, product: product, option_values: variant1.option_values)
end
it "should validate that option values are unique for every variant" do
#This is the main test. This should return false according to my uniqueness validation. But its not since in the custom uniqueness validation method product.variants returns empty and hence its not going inside the each block.
puts #variant2.valid?
expect(true).to be true #just so that the test will pass. Not actually what I want to put here
end
end
end
end
Anybody know whats wrong here. Thanks in advance
I have a guess at what's happening. I think a fix would be to change your validation with the following line:
product.variants.reload.each do |v|
What I think is happing is that when you call variant1 in your test, it is running the validation for variant1, which calls variants on the product object. This queries the database for related variants, and gets an empty result. However, since variant2 has the same actual product object, that product object will not re-query the database, and remembers (incorrectly) that its variants is an empty result.
Another change which might make your test run is to change your test as follows:
before do
#variant2 = FactoryBot.create(:variant, product_id: product.id, option_values: variant1.option_values)
end
It is subtle and I'd like to know if it works. This sets the product_id field on variant2, but does not set the product object for the association to be the actual same product object that variant1 has. (In practice this is more likely to happen in your actual code, that the product object is not shared between variant objects.)
Another thing for your correct solution (if all this is right) is to do the reload but put all your save code (and your update code) in a transaction. That way there won't be a race condition of two variants which would conflict, because in a transaction the first must complete the validation and save before the second one does its validation, so it will be sure to detect the other one which just saved.
Some suggested debugging techniques:
If possible, watch the log to see when queries are made. You might have caught that the second validation did not query for variants.
Check the object_id. You might have caught that the product objects were in fact the same object.
Also check new_record? to make sure that variant1 saved before you tested variant2. I think it does save, but it would have be nice to know you checked that.

Includes with a related element

I would like to use the includes method with the related element of my Post
My Post can be associated with different type of element. And I use a value :cat to knows witch kind of element is associated.
The value work as this (cat: (1 => Message, 2=>Question, 3=>Task, 4=>Event) with the association has_one
Example : If post.cat == 3, I can call the task related with a method post.task
Now, I would like to optimize the SQL requests of my Post/Index with the method includes. But is not working for the moment. Can you help me to find the error of my code ?
Post_controller :
def index
#posts = current_user.posts
#posts.each do |post|
if post.cat == 3
#task = post.task.includes(:users)
elsif post.cat == 4
#event = post.event.includes(:reminds)
end
end
end
Error: undefined method `includes'
Edit :
Post_model:
class Post < ApplicationRecord
has_one :post_message, dependent: :destroy
has_one :question, dependent: :destroy
has_one :task, dependent: :destroy
has_one :event, dependent: :destroy
end
Task_model :
class Task < ApplicationRecord
belongs_to :post
has_many :users_task, dependent: :destroy
has_many :users, through: :users_task
end
Why are you using #posts.each ?
For me, the best solution for that is to find all the posts whith the defined cat to run the includes method. In your case, it would be like that :
#posts.where(cat: 1).includes(:message)
#posts.where(cat: 2).includes(:question)
#posts.where(cat: 3).includes(task: :users)
#posts.where(cat: 4).includes(event: :reminds)
Well, after many tries, I opted for a scope method to run the includes method. It's not a really elegant solution, but I think it's the best in my case.
So I'm preparing the scopes in my Post_Model:
scope :with_tasks, -> { where(cat: 3).includes(:user).includes(task: :users) }
scope :with_events, -> { where(cat: 4).includes(:user).includes(event: :reminds) }
And after, I render them in my index action like this :
#posts = current_user.posts.with_tasks + current_user.posts.with_events
So the code is generating 2 SQL Requests to find the posts (one for each category).
I think there is a way to join all that directly into a new global scope, but I don't know how. So if there is anyone knows that, he can edit the answer
Enjoy !
If you're getting an undefined method: 'includes' error, it means that either post.task or post.event are not returning ActiveRecord objects like your code is expecting. Are you sure there will always be values set for .task or .event at that point in execution? Are there any cases where that value might be nil or blank?
By the way, have you heard about 'polymorphic associations'? Defining an association as polymorphic allows you to associate records of arbitrary types with a specific column (by storing both object ID and class name on each record behind the scenes). It seems like this exactly matches your use case. It would be much easier to use the built-in mechanism than trying to do all the if-then switching based on category in your code.

Including an association if it exists in a rails query

Update: This may be something that just isn't doable. See this
TLDR: How do you conditionally load an association (say, only load the association for the current user) while also including records that don't have that association at all?
Rails 3.1, here's roughly the model I'm working with.
class User
has_many :subscriptions
has_many :collections, :through => :subscriptions
end
class Collection
has_many :things
end
class Thing
has_many :user_thing_states, :dependent => :destroy
belongs_to :collection
end
class Subscription
belongs_to :user
belongs_to :collection
end
class UserThingState
belongs_to :user
belongs_to :thing
end
There exist many collections which have many things. Users subscribe to many collections and thereby they subscribe to many things. Users have a state with respect to things, but not necessarily, and are still subscribed to things even if they don't happen to have a state for them. When a user subscribes to a collection and its associated things, a state is not generated for every single thing (which could be in the hundreds). Instead, states are generated when a user first interacts with a given thing. Now, the problem: I want to select all of the user's subscribed things while loading the user's state for each thing where the state exists.
Conceptually this isn't that hard. For reference, the SQL that would get me the data needed for this is:
SELECT things.*, user_thing_states.* FROM things
# Next line gets me all things subscribed to
INNER JOIN subscriptions as subs ON things.collection_id = subs.collection_id AND subs.user_id = :user_id
# Next line pulls in the state data for the user
LEFT JOIN user_thing_states as uts ON things.id = uts.thing_id AND uqs.user_id = :user_id
I just don't know how to piece it together in rails. What happens in the Thing class? Thing.includes(:user_thing_states) would load all states for all users and that looks like the only tool. I need something like this but am not sure how (or if it's possible):
class Thing
has_many :user_thing_states
delegates :some_state_property, :to => :state, :allow_nil => true
def state
# There should be only one user_thing_state if the include is correct, state method to access it.
self.user_thing_states.first
end
end
I need something like:
Thing.includes(:user_question_states, **where 'user_question_state.user_id => :user_id**).by_collections(user.collections)
Then I can do
things = User.things_subscribed_to
things.first.some_state_property # the property of the state loaded for the current user.
You don't need to do anything.
class User
has_many :user_thing_states
has_many :things, :through => :user_thing_states
end
# All Users w/ Things eager loaded through States association
User.all.includes(:things)
# Lookup specific user, Load all States w/ Things (if they exist for that user)
user = User.find_by_login 'bob'
user.user_thing_states.all(:include => :things)
Using includes() for this already loads up the associated object if they exist.
There's no need to do any filtering or add extra behavior for the Users who don't have an associated object.
Just ran into this issue ourselves, and my coworker pointed out that Rails 6 seems to include support for this now: https://github.com/rails/rails/pull/32655
*Nope, didn't solve it :( Here's a treatment of the specific issue I seem to have hit.
Think I've got it, easier than expected:
class Thing
has_many :user_thing_states
delegates :some_state_property, :to => :state, :allow_nil => true
scope :with_user_state, lambda { |user|
includes(:user_thing_states).where('user_thing_states.user_id = :user_id
OR user_thing_states.user_id IS NULL',
{:user_id => user.id}) }
def state
self.user_thing_states.first
end
end
So:
Thing.with_user_state(current_user).all
Will load all Things and each thing will have only one user_question_state accessible via state, and won't exclude Things with no state.
Answering my own question twice... bit awkward but anyway.
Rails doesn't seem to let you specify additional conditions for an includes() statement. If it did, my previous answer would work - you could put an additional condition on the includes() statement that would let the where conditions work correctly. To solve this we'd need to get includes() to use something like the following SQL (Getting the 'AND' condition is the problem):
LEFT JOIN user_thing_states as uts ON things.id = uts.thing_id AND uqs.user_id = :user_id
I'm resorting to this for now which is a bit awful.
class User
...
def subscribed_things
self.subscribed_things_with_state + self.subscribed_things_with_no_state
end
def subscribed_things_with_state
self.things.includes(:user_thing_states).by_subscribed_collections(self).all
end
def subscribed_things_with_no_state
Thing.with_no_state().by_subscribed_collections(self).all
end
end

rails has_many :through table don't get saved

I am new to rails so beware of the ugly code.
I have these models
class User < ActiveRecord::Base
has_many :games_playeds
has_many :games, :through => :games_playeds
end
class Game < ActiveRecord::Base
has_many :games_playeds
has_many :users, :through => :games_playeds
end
class GamesPlayed < ActiveRecord::Base
validates_presence_of :user_id, :game_id
belongs_to :user
belongs_to :game
end
Game describe a game independent of any user
GamesPlayed describe how users behaved on that game (deaths, current stage, wins, etc)
In each stage of this game the user can choose among several choices, some will get to later stages, some will make him go back. The point is that once a choice is made in one stage I don't allow to choose anything else.
To implement this I have a steps attribute that encode the previous choices like "0:1;1:6;6:2" and so on. This attribute in on the GamesPlayed model.
The pages the user navigates are automatically generated so I don't know their names but I know they are called XX_to_YY. I have a method in my controller that will get them all and do something as ugly as this:
#get the game name, we have several games
game = Game.find_by_name (params[:game])
#get the previous and current stage
from, to = params[:page].to_s.split("_to_")
to = to.split(".html")[0]
played = current_user.games_playeds.find_by_game_id (game.id)
steps = []
played.steps.split(";").each {|a| steps << a.split(":").first}
if steps.include? from
render :inline => "You already chose for this, go back"
else
played.steps << "#{from}:#{to};"
played.save
# pl = current_user.games_playeds.find_by_game_id (game.id)
# raise pl.steps
render "games/choosePath/#{game.name}/#{params[:page]}.html"
end
I guess it is a horrible code. I am new to Ruby as well :P
Now, the question:
played.save gives me no errors.
# pl = current_user.games_playeds.find_by_game_id (game.id)
# raise pl.steps
will "print" the correct data but it is not saved in the database! I use sqlitebrowser to visually inspect it and I am sure it is not saved.
BTW, as second question, if someone knows how to get to the association object without that ugly code above very thankful also.
and third and last question:
steps = []
played.steps.split(";").each {|a| steps << a.split(":").first}
This is also horrible but don't know how to make it better (want to get the aa and bb from "aa:cc;bb:dd;" I don't know what is aa and bb, it can be numbers or words.
If you want to raise an exception when save fails, call save!; otherwise if you continue to use save you should check the returned boolean to see if the save was successful.
A false return value will indicate that validations have failed. The details of the failures will be in the error information on the model.
About getting the association in a better way: there is probably something you could do with scopes or even just by writing a method to encapsulate what you are trying to do.
With regard to decoding the steps, you could use inject instead of each but it would still be quite logic heavy. I would suggest encapsulating it in a method with a descriptive name, like decode_steps or similar.

Elegantly selecting attributes from has_many :through join models in Rails

I'm wondering what the easiest/most elegant way of selecting attributes from join models in has_many :through associations is.
Lets say we have Items, Catalogs, and CatalogItems with the following Item class:
class Item < ActiveRecord::Base
has_many :catalog_items
has_many :catalogs, :through => :catalog_items
end
Additionally, lets say that CatalogueItems has a position attribute and that there is only one CatalogueItem between any catalog and any item.
The most obvious but slightly frustrating way to retrieve the position attribute is:
#item = Item.find(4)
#catalog = #item.catalogs.first
#cat_item = #item.catalog_items.first(:conditions => {:catalog_id => #catalog.id})
position = #cat_item.position
This is annoying because it seems that we should be able to do #item.catalogs.first.position since we have completely specified which position we want: the one that corresponds to the first of #item's catalogs.
The only way I've found to get this is:
class Item < ActiveRecord::Base
has_many :catalog_items
has_many :catalogs, :through => :catalog_items, :select => "catalogue_items.position, catalogs.*"
end
Now I can do Item.catalogs.first.position. However, this seems like a bit of a hack - I'm adding an extra attribute onto a Catalog instance. It also opens up the possibility of trying to use a view in two different situations where I populate #catalogs with a Catalog.find or with a #item.catalogs. In one case, the position will be there, and in the other, it won't.
Does anyone have a good solution to this?
Thanks.
You can do something like this:
# which is basically same as your "frustrating way" of doing it
#item.catalog_items.find_by_catalogue_id(#item.catalogs.first.id).position
Or you can wrap it into in an instance method of the Item model:
def position_in_first_catalogue
self.catalog_items.find_by_catalogue_id(self.catalogs.first.id).position
end
and then just call it like this:
#item.position_in_first_catalogue
Just adding answer so that it might help others
CatalogItem.joins(:item, :catalog).
where(items: { id: 4 }).pluck(:position).first
You should be able to do #catalog.catalog_item.position if you provide the other end of the association.
class Catalog < ActiveRecord::Base
belongs_to :catalog_item
end
Now you can do Catalog.first.catalog_item.position.
Why don't You just
#item = Item.find(4)
position = #item.catalog_items.first.position
why do you go through catalogs? It doesn't make any sense to me since you are looking for first ANY catalog!?

Resources