How do I create both a main and nested ActiveAdmin resource? - ruby-on-rails

I have an Order resource, nested under User:
ActiveAdmin.register Order do
belongs_to :user
end
# Routes at:
# /admin/users/:user_id/orders/...
I would now also like to create an Order resource, for an overall view. Ideally I'd just do:
ActiveAdmin.register Order do
end
# Routes at:
# /admin/orders/...
But this doesn't work, because it's creating the same underlying class (I assume).
it appears based on this that I should be able to use as: 'all_orders', but in fact this still appears to affect the same class, and ends up with routes like /admin/users/:user_id/all_orders/...
So, how can I have both order resources set up and operating independently, both using orders in the URL?

I think this might be the best option, as detailed here:
ActiveAdmin.register Order do
belongs_to :user, optional: true
end
# Routes at:
# /admin/orders/...
# /admin/users/:user_id/orders/...
I would like to have the option of doing different things for the two, so an option where they can be separately defined would still be appreciated. If no better options are available I'll leave this answer here as it's reasonable.

Another solution, which is very hacky but does provide what I need is this:
# models/order.rb
class Order < ActiveRecord::Base
belongs_to :user
end
# models/order_alias.rb
class OrderAlias < Order
end
# admin/user/order.rb
ActiveAdmin.register Order do
belongs_to :user
end
# admin/order.rb
ActiveAdmin.register OrderAlias, as: 'AllOrder' do
menu label: 'Orders'
index title: 'Orders' do
# ...
end
end
This still has all_orders in the URL, but it's the closest to a solution I can find. Anything more elegant much appreciated.

Related

ActiveAdmin how to Decorate associated links

In ActiveAdmin, I know I can use decorators, like Draper, to feed display_name and name, but how do I use the decorator for simple association links (i.e. auto_link(resource))?
Given I have a Post & a Comment:
# Post.rb
class Post
has_many :comments
end
# Comment.rb
class Comment
belongs_to :post
end
# decorators/post_decorators.rb
class PostDecorator
def name
"Custom Post Name ##{object.id}"
end
end
# admin/post.rb
ActiveAdmin.register Post do
delegate_with PostDecorator
end
# admin/comments.rb
ActiveAdmin.register Comment do
index do
# ...
column :post
# ...
end
show do
default_main_content
end
end
When viewing the Comment ActiveAdmin area, the show's default_main_content and the index's column :post both link automatically to the Post object, but never use the decorator.
I will see: Post #4 instead of Custom Post Name #4 in those sections.
When I visit the Post admin area, it will use the decorated name perfectly fine.
How do I get automatic links to use Draper throughout the entire admin area?
I currently have a def name on the object itself, but that is a display property and want to move it to a Decorator.
If you're using Draper, you can use decorates_association to tell one decorator to decorate its associations. This requires that you have a CommentDecorator.
class CommentDecorator < Draper::Decorator
delegate_all
decorates_association :post
end
ActiveAdmin.register Comment do
decorate_with CommentDecorator
...
end
#nitsujri you can write a draper concern that you can include on all of your decorators that functionally handles all associations for you. Like you I was also tired of having to manage the associations myself - it meant keeping track of associations in another place.
Here is the simple concern that relies on using activerecord reflection to pull all of the names off of the existing object and throwing them to drapers decorates_associations method.
module AutoDecorateAssociations
extend ActiveSupport::Concern
included do
delegate :class, to: :object, prefix: true
decorates_associations *(object_class.reflect_on_all_associations.map(&:name) - [:versions])
end
end
and then just include AutoDecorateAssociations on the decorators you don't want to have to keep track of (unfortunately you can't toss it in your application_decorator)

Rails ActiveAdmin has_one and belongs_to causes 'Undefined Method for <PLURAL_RESOURCE>'

In Rails, I have a 'User' model and a 'Wallet' model. A 'User' has_one wallet and each 'Wallet' belongs_to a 'User'. I made a 'Show' page in ActiveAdmin to view a User's Wallet. However, going to that page returns this error:
undefined method `wallets' for #<User:0x007f...>
HOWEVER, when I update the User model to 'has_many :wallets' instead of ':has_one wallet', everything works. Here is the relevant code from my models and ActiveAdmin code:
Models:
class User < ActiveRecord::Base
has_one :wallet, dependent: :destroy
end
class Wallet < ActiveRecord::Base
belongs_to :user
end
ActiveAdmin:
ActiveAdmin.register Wallet do
belongs_to :user
actions :all, except: :destroy
show do
div do
'hello'
end
end
end
ActiveAdmin.register User do
actions :all, except: :destroy
permit_params
action_item :wallet, only: :show do
link_to('Wallet', admin_user_wallet_path(user, user.wallet.id))
end
index do...
end
Any ideas as to where I might have gone wrong?
Edit 1: updates to correct colon placement mistakes in description
Edit 2:
in response to:
Can you show your routes file? Also, can you give us the full traceback of the error message and give us the output of rake routes? I suspect that the reason it's complaining about wallets not being defined (even though you never call wallets in the above code) is that some routing is making assumptions about how the relationships look. – Glyoko 4 mins ago
My routes file contains no mention 'wallet' or 'wallets'.
My stack error more specifically looks like this:
activemodel (4.1.15) lib/active_model/attribute_methods.rb, line 435
Let me know if you need more than that.
Here's the related output from 'bin/rake routes':
admin_user_wallets GET /admin/users/:user_id/wallets(.:format) admin/wallets#index
POST /admin/users/:user_id/wallets(.:format) admin/wallets#create
new_admin_user_wallet GET /admin/users/:user_id/wallets/new(.:format) admin/wallets#new
edit_admin_user_wallet GET /admin/users/:user_id/wallets/:id/edit(.:format) admin/wallets#edit
admin_user_wallet GET
/admin/users/:user_id/wallets/:id(.:format) admin/wallets#show
admin_user_wallet PATCH /admin/users/:user_id/wallets/:id(.:format) admin/wallets#update
admin_user_wallet PUT /admin/users/:user_id/wallets/:id(.:format) admin/wallets#update
ActiveAdmin uses InheritedResources gem internally, the belongs_to method ends up inside InheritedResources.
Possible solution here
ActiveAdmin.register Wallet do
belongs_to :user, singleton: true
actions :all, except: :destroy
end
The option singleton: true makes the Wallet a singular resource for the User.
Probably, another option optional: true may be helpful if Wallet is not required for any User to present
Even though your routes may not explicitly reference wallet(s), there may be something there making assumptions about how records are related to each other.
Look at the output of rake routes, in particular:
admin_user_wallet GET
/admin/users/:user_id/wallets/:id(.:format) admin/wallets#show
When you call admin_user_wallet_path(user, user.wallet.id) it's matching the /admin/users/:user_id/wallets/:id(.:format) route. Notice how that expects both a user id and a wallet id in the path. This is a tip-off that something is off here, since if you have the user, there should be exactly one wallet associated with it. You shouldn't need to give both the user and wallet id.
Since the wallet resource is nested under users, the page where you view the user's wallet is actually more of an index page than a show. If the wallet were an independent resource, then you could have a path like /admin/wallets/:id and things would work out fine.
But since the wallet is a subresource of the user, you would ideally want a path like /admin/users/:user_id/wallet. There's no need to pass the wallet id, since you already have the user.
tl;dr: Try changing the shows to indexs and see where that gets you. e.g.
index do
div do
'hello'
end
end
# ...
action_item :wallet, only: :index do
link_to('Wallet', admin_user_wallets_path(user))
end
Okay.. So I had this same exact issue. I had a belongs_to a parent where the parent had only a has_one to the child model..... Nothing seemed to work so I decided to fake it. I am not sure if this is the best way to do this but it worked. In the parent model, add a method:
class User < ActiveRecord::Base
has_one :wallet
def wallets
Wallet.where(user_id: id)
end
end
The above code is a hotfix until I can find some other way to implement what I need.

Ruby on Rails Association build and assign 2 related associations

So I've got a User model, a Building model, and a MaintenanceRequest model.
A user has_many :maintenance_requests, but belongs_to :building.
A maintenance requests belongs_to :building, and belongs_to: user
I'm trying to figure out how to send a new, then create a maintenance request.
What I'd like to do is:
#maintenance_request = current_user.building.maintenance_requests.build(permitted_mr_params)
=> #<MaintenanceRequest id: nil, user_id: 1, building_id: 1>
And have a new maintenance request with the user and building set to it's parent associations.
What I have to do:
#maintenance_request = current_user.maintenance_requests.build(permitted_mr_params)
#maintenance_request.building = current_user.building
It would be nice if I could get the maintenance request to set its building based of the user's building.
Obviously, I can work around this, but I'd really appreciate the syntactic sugar.
From the has_many doc
You can pass a second argument scope as a callable (i.e. proc or lambda) to retrieve a specific set of records or customize the generated query when you access the associated collection.
I.e
class User < ActiveRecord::Base
has_many :maintenance_requests, ->(user){building: user.building}, through: :users
end
Then your desired one line should "just work" current_user.building.maintenance_requests.build(permitted_mr_params)
Alternatively, if you are using cancancan you can add hash conditions in your ability file
can :create, MaintenanceRequest, user: #user.id, building: #user.building_id
In my opinion, I think the approach you propose is fine. It's one extra line of code, but doesn't really increase the complexity of your controller.
Another option is to merge the user_id and building_id, in your request params:
permitted_mr_params.merge(user_id: current_user.id, building_id: current_user.building_id)
#maintenance_request = MaintenanceRequest.create(permitted_mr_params)
Or, if you're not concerned about mass-assignment, set user_id and building_id as a hidden field in your form. I don't see a tremendous benefit, however, as you'll have to whitelist the params.
My approach would be to skip
maintenance_request belongs_to :building
since it already belongs to it through the user. Instead, you can define a method
class MaintenanceRequest
belongs_to :user
def building
user.building
end
#more class stuff
end
Also, in building class
class Building
has_many :users
has_many :maintenance_requests, through: :users
#more stuff
end
So you can completely omit explicit building association with maintenance_request
UPDATE
Since users can move across buildings, you can set automatic behavior with a callback. The job will be done like you do it, but in a more Railsey way
class MaintenanceRequest
#stuff
before_create {
building=user.building
}
end
So, when you create the maintenance_request for the user, the building will be set accordingly

Restrict routes to certain users in Rails app

In my rails v4 app, users belong to a single group.
class User < ActiveRecord::Base
belongs_to :group
...
Each group can have many projects,
class Group < ActiveRecord::Base
has_many :projects
has_many :users
...
Each project can have many experiments, in a one to many relationship.
In my routes, I have:
resources :projects do
resources :experiments do
...
end
end
What I'd like to do is only allow users to access projects and experiments if the project has the same group_id as the user (i.e. if user enters a project id parameter in the projects#show route for a project outside of their group, it will not be displayed). Is there a clean way to implement this without having to do multiple checks in the view?
Take a look at building a custom constraint based on Group membership:
http://guides.rubyonrails.org/routing.html#advanced-constraints
Extremely simple example (obviously, you'll need to match your project design):
class GroupConstraint
  def initialize
#project = Project.find(params[:id])
    #user = current_user
  end
 
  def matches?(request)
    #user.groups.include?(#project.group)
  end
end
Then in your routes:
resources :projects, constraints: GroupConstraint.new do
resources :experiments do
...
end
end
This is authorization problem, so, as for me, it's better to define what users can and can not see using any auhtorization library, not using routes or something like that. Because you will, for example, definitely want to find out should you display link on given group in views, which groups is available for current user and so on.
Take a look on cancancan for example: https://github.com/CanCanCommunity/cancancan.

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

Resources