inertiajs / inertia-rails Goto Github PK
View Code? Open in Web Editor NEWThe Rails adapter for Inertia.js.
Home Page: https://inertiajs.com
License: MIT License
The Rails adapter for Inertia.js.
Home Page: https://inertiajs.com
License: MIT License
The current implementation of inertia_share
is based on before_action
, so the shared data is executed by all means before the action is processed. Even if the controller action raises an exception, which I don't think is a good thing.
Think of this application using a custom exception handler to response with Inertia for exceptions, like this:
# app/config/application.rb
module MyApplication
class Application < Rails::Application
# ...
config.exceptions_app = ->(env) { ExceptionsController.action(:show).call(env) }
end
end
# app/controllers/exceptions_controller.rb
class ExceptionsController < ActionController::Base
def show
render inertia: 'Error', props: {
status: request.path_info[1..-1].to_i
}
end
end
This works fine, see my my demo Rails app PingCRM for a live example:
https://pingcrm.ledermann.dev
Now, lets assume an action raises an error, like this:
class ApplicationController < ActionController::Base
inertia_share do
# complex logic here
end
end
class DashboardController < ApplicationController
inertia_share do
# more complex logic here
end
def index
1/0
render inertia: 'Dashboard', props: {}
end
end
When the error occurs, the exception handler strikes in and renders the Error
Page instead of the Dashboard
page, but the shared data of ApplicationController
and DashboardController
is included as props. too. This is not optimal, because in case of an exception the response should be as simple as possible.
I would like to propose again to merge my PR #17 because it has not this issue.
Let's get this on Rubygems so gem install
works!
After upgrading to 1.12.1, a gem I wrote is now throwing an error when it runs. I'm not sure if this is something which might effect others, or if it's a sub-optimal implementation on my part.
In my gem, I use Rails.application.eager_load!
so that I can load all ActiveRecord models and do some inspection. With the latest version, that throws the following error:
undefined method 'helper' for ActionController::API:Class
Which traces back to this line on the Controller module in InertiaRails.
I've been searching for a better way to eager load models, but I can't seem to find one. Would appreciate some guidance.
Hey there folks! Thanks so much for your ongoing maintenance of this adapter. โค๏ธ
I recently updated the Laravel adapter to automatically share validation errors. You can read more about that in the release notes here.
Would it makes sense do add this kind of functionality to the Rails adapter as well? ๐ค
Like React, the convention for Svelte components is to use proper case (LikeThis) but Rails expects the default paths to be lowercase. It works (so far) if I change it to lowercase but I can see issues going forward and there should be a way to accept components named conventionally.
Below is a screenshot of what I had to do to get the show
method to work - either use the more explicit render
method with a named path as the first argument or change the .svelte
file to lowercase:
I've build an example app on how to use Inertia.js with Rails using this gem. Maybe it's worth to add a link to the README:
I recently ran into an issue where the "Sign Out" button of my app would occasionally result in an inertia modal w/ 404 error page.
I opened this as inertiajs/inertia#419 on the main Inertia repo, but they kindly helped me dig a bit deeper and I've now confirmed that the issue is that response status code.
At this point I'm guessing the issue is somewhere in my app / middleware stack, but I wanted to share here in case you folks have any thoughts as to how this might be happening.
I'm specifically running into this with the "Sign Out" button in my app. The problem flow is.
I've found this tricky to reproduce as most cases send the correct 303 status code, but I have been able to reproduce it.
For reference, here's my middleware stack.
use Rack::Cors
use Honeybadger::Rack::UserInformer
use Honeybadger::Rack::UserFeedback
use Honeybadger::Rack::ErrorNotifier
use Rack::Rewrite
use ActionDispatch::SSL
use Rack::Sendfile
use ActionDispatch::Static
use Rack::Deflater
use ActionDispatch::Executor
use ActiveSupport::Cache::Strategy::LocalCache::Middleware
use RailsAutoscaleAgent::Middleware
use Rack::Runtime
use Rack::MethodOverride
use ActionDispatch::RequestId
use Rack::Timeout
use RequestStore::Middleware
use ActionDispatch::RemoteIp
use Rails::Rack::Logger
use ActionDispatch::ShowExceptions
use ActionDispatch::DebugExceptions
use Rollbar::Middleware::Rails::RollbarMiddleware
use ActionDispatch::Callbacks
use ActionDispatch::Cookies
use ActionDispatch::Session::CookieStore
use ActionDispatch::Flash
use ActionDispatch::ContentSecurityPolicy::Middleware
use Rack::Head
use Rack::ConditionalGet
use Rack::ETag
use Rack::TempfileReaper
use Clearance::RackSession
use Warden::Manager
use Coverband::BackgroundMiddleware
use Rack::Attack
use ScoutApm::Middleware
use InertiaRails::Middleware
run MyApp::Application.routes
Any thoughts? (I'll also certainly understand if you want to close this under the assumption that the problem is on my side, but figured it was worth an ask).
SSR is a great tool for SEO oriented projects.
So we expect to get html for common requests, but it doesn't make sense to retrieve html on real user after loading first page (X-Inertia requests)
I opened PR #75
Another point is to have regress-strategy if node server fails or doesn't run (during restart time).
Really appreciate inertia project. So please leave me a comment
In my local test app, if i change (or remove) shared data, the old data is still sent to the component.
i.e. setting in the controller
inertia_share test: 'thing'
making a request, then changing the controller to:
inertia_share test: 'another thing'
sends { "test": "thing" }
to the controller.
I believe we maybe aren't merging shared data correctly or something like that.
Note:This also could be due to the fact I'm running the app through Docker for Mac... sometimes Docker will cache classes if you don't have the right setting in your development.rb
. I don't think that's the case here, but noting it in case someone else picks this up.
I've been using the spec helper and I've run into an issue where I'm seeing "Inertia test helpers aren't set up!", despite the fact that they are indeed set up. In my case I ran into this when a before_action
that I was not expecting to run did end up running, and thus I never got to the render(inertia ...
call.
This seems to be due to the fact that the stubbing of render
method is done lazily when the render(inertia ...
is actually called.
Presuming these spec helpers are intended for use in applications and not just for the library itself (which I really hope is the intention as they're great!), I think it would be great to look into fixing this as it can lead to a confusing experience. I'd be happy to poke around and see if I could resolve this and open a PR if I could, but wanted to start with an issue to see if there are any existing thoughts or constraints I'm unaware of.
Thanks again for the great library!
Per #48
Inertia Rails automatically uses your default application layout. If you'd like to change that, you can do so via the Inertia config.
How I can set root layout dynamically?
I have two devise models, user, and customer
Based on the type I use different layouts but inertia sets root layout at config, is it possible to change the layout dynamically at a controller level?
Thanks
Hey inertia-rails team, first of all, thanks for the great work on this project ๐!
I unfortunately was unable to get the tests running locally as I'm hitting the following error:
An error occurred while loading rails_helper.
Failure/Error: 'Cache-Control' => "public, max-age=#{1.hour.to_i}"
NoMethodError:
undefined method `hour' for 1:Integer
# ./spec/dummy/config/environments/test.rb:19:in `block in <top (required)>'
# ./spec/dummy/config/environments/test.rb:6:in `<top (required)>'
# ./spec/dummy/config/environment.rb:5:in `<top (required)>'
# ./spec/rails_helper.rb:4:in `require'
# ./spec/rails_helper.rb:4:in `<top (required)>'
No examples found.
No examples found.
I'm guessing there's some setup step needed in the spec/dummy app or similar, but not sure what it is. I'd be more than happy to document or add to bin/setup
if you point me in the right direction.
One use case for shared data is to provide defaults that individual controllers and actions can override. For example, meta tag data:
class ApplicationController
# Let's assume the frontend knows how to digest this and print it to the page
inertia_share do
{
meta: {
title: 'Who is the GOAT?',
description: 'A place for Brandon and Brian to debate Jordan vs. Brady',
}
}
end
end
class HockeyController < ApplicationController
def index
render inertia: 'HockeyPage', props: {
meta: {
title: 'Who is the hockey GOAT?',
description: 'Probably Gretzky, right?',
}
}
end
end
No issues so far! But it's a pain when you only want to overwrite some of the props, like:
class BasketballController < ApplicationController
def index
render inertia: 'BasketballPage', props: {
meta: {
title: 'Who is the basketball GOAT?',
# I want the default description
}
}
end
end
Solving this is not difficult; we just need to deep merge props fed to the renderer into the shared data.
The tricky parts are whether this should be opt-in behavior and whether or not it should be default behavior.
Hi,
First of all thanks for the rails adapter for Inertia!
I'm planing to use the shared_data
functionality to send the current user, locale, menu items ... but I think that is not possible right now, let me explain:
If I use the examples on the docs (https://inertiajs.com/shared-data#sharing-data) they work for synchronously and partially for the lazily case, because we don't have access to the controller instance inside the block, so we can't call the url helpers, flash, current_user, methods, etc, true?
In case that this is true:
Are you using another approach to send this data to Inertia? Or are you rendering the entire layout in Rails and only the content part with Inertia (not tested) ? Is this intended or can this be an improvement?
The recent change to fix broken partial reloads causes shared props to come in with symbols and the rest to be strings when using have_exact_props
in a request spec.
class SomeController < ApplicationController
inertia_share someProperty: -> {
{
property_a: "some value",
property_b: "this value"
}
}
def some_method
render inertia: "Manager/AwayServices", props: { property_c: "some other value" }
end
end
If I then test this using:
expect_inertia.to have_exact_props({
someProperty: {
property_a: "some value",
property_b: "this value",
},
property_c: "some other value"
})
I end up with a mismatch because the shared properties have symbols and the props in the method have strings for the keys. This worked fine in 3.0.0. I haven't tested 3.1.0.
Hello, I found a bug in the InertiaRails::Renderer#partial_keys method
in lhs,
def partial_keys # return a symbol array
(@request.headers['X-Inertia-Partial-Data'] || '').split(',').compact.map(&:to_sym)
end
and at rhs, AbstractController::Rendering#view_assigns
def view_assigns # return a string (keys) hash
variables = instance_variables - _protected_ivars
variables.each_with_object({}) do |name, hash|
hash[name.slice(1, name.length)] = instance_variable_get(name)
end # name.slice(1, name.length) return a string
end
so in InertiaRails::Renderer#props
def props
_props = ::InertiaRails.shared_data(@controller).merge(@props).select do |key, prop|
if rendering_partial_component?
key.in? partial_keys # here, it's alwas false (key is a string, partial_keys are symbols)
else
!prop.is_a?(InertiaRails::Lazy)
end
end
deep_transform_values(_props, lambda {|prop| prop.respond_to?(:call) ? @controller.instance_exec(&prop) : prop })
end
the result of the bug is that partial reloading with use_inertia_instance_props isn't working correctly
Stani.
Monkey patch:
# fixing InertiaRails::Renderer#partial_keys method
module InertiaRails
class Renderer
private
define_method(:_partial_keys, instance_method(:partial_keys))
def partial_keys
_partial_keys.map { |key| key.to_s }
end
end
end
I will refer to Svelte in the following text because it's the one I currently use, however it's interchangeable with any supported frontend works such as React, Vue, ...
Allow to render Svelte page components only when really needed in order to save development cost and time.
Per controller action, it would be great to be able to render static HTML/ERB/Slim/HAML view inside a Svelte component.
Tools such as simple_form can be a life saver when it comes to development speed and this introduce the ability to keep using these powerful librairies and all Rails view engine features
Updating the render inertia: ...
syntax without introducing any breaking changes.
render inertia: true # No change
render inertia: "projects/show" # No change
render inertia: { component: true } # Same as true. Just there for the sake of completeness
render inertia: { component: "projects/show" } # Save as "projects/show". Just there for the sake of completeness
render inertia: { static: true } # Will render an HTML/ERB view using controller_path/action_name
render inertia: { static: "projects/show" } # Will render an HTML/ERB view with the given path
How static would work
It would work exactly the same as the current behavior. It would still render the same HTML layout and still render the same HTML/JSON response without any extra HTML tag:
<div id="app" data-page="...">
However, the page structure would change just a little
{
:component=>"static", <-- This would render a Svelte's component that receives the HTML (body) as a props
:component=>nil, <-- This wouldn't render any component, however if Inertia renders a layout, that layout will receive the HTML (body) as a props
:props=>{
body: "HTML encoded partial view with layout: false of the static ERB view"
body: "<p>My static view>" <-- <p>My static view</p>
},
:url=>"/",
:version=>"cdf95f49b18b571fa55f57e90df7fb7f84865fe1"
}
A static svelte component (could be a layout or a view) would be this simple:
<script lang="ts">
export let body: string;
</script>
{@html body}
I have written a renderer override to allow testing the idea. Simply put this in an initializer
module InertiaRails
module RendererExtension
def initialize(component, controller, request, response, render_method, props: nil, view_data: nil, deep_merge: nil)
super
component.deep_symbolize_keys! if component.is_a?(Hash)
@static = component.is_a?(Hash) && component.key?(:static)
@component = extract_component(component)
end
private
def page
super.deep_merge(
component: @static ? inertia_static_component : component,
props: @static ? static_rendered_view : {}
)
end
def extract_component(component)
value = component.is_a?(Hash) ? component[:component] || component[:static] : component
return "#{@controller.controller_path}/#{@controller.action_name}" if value.is_a?(TrueClass)
value
end
def static_rendered_view
return nil unless @static
{ body: @controller.render_to_string(component, layout: false) }
end
def inertia_static_component
return @controller.send(:inertia_static_component) if @controller.respond_to? :inertia_static_component
nil
end
end
end
InertiaRails::Renderer.prepend InertiaRails::RendererExtension
So I just added "lazy props" to the Laravel adapter: inertiajs/inertia-laravel#175. It would be awesome to bring this same behaviour to the Rails adapter.
Lazy props are simply data that's not included on the initial visit to a page. It's only ever included when doing partial reloads, using the only
key.
It was actually very easy to implement in the Laravel adapter. I created a new LazyProps
class, that acts a "marker" for these props. Then, on regular (non partial reload) visits, I simply filter these props out.
#38 introduced a serious bug within InertiaRails.version
: It returns nil
for every server response, so asset versioning is broken, which means the frontend will not be notified if the assets have changed.
Why? To me it seems to be caused by the thread-safe change. Now there is threadsafe_version
, so changing the version in one thread is not shared with other threads. This seems to be intended, because there is an explicit test for this.
IMHO the thread handling is not correct. Typically, the version is set just one time within an initializer. Using a multi threaded application server like Puma spawns some new threads. So far as I know, spawning a new thread does not run the initializers again, so the Thread.current
does not include the thread_safe_version
for all running threads.
Try this is out in a Rails application using inertia_rails v1.4.0:
rails c
(irb)> InertiaRails.version.inspect
=> "1.0"
(irb)> thread = Thread.new { p InertiaRails.version.inspect }
"nil"
IMHO, the layout
config has the same issue, but because it has a fallback, it will never be nil
.
Hi there,
One nice feature of ActiveModelSerializer-based rendering is the implicit serialization of instances of ActiveRecord::Base. See: https://github.com/rails-api/active_model_serializers/blob/v0.10.6/docs/general/getting_started.md#rails-integration
Would there be any appetite or interest for this behavior with the inertia
renderer?
For example, say we have this render at the end of a controller action:
class SomeController < ApplicationController
def show
@post = Post.find(params[:id])
render(inertia: 'SomeComponent',
props: { post: @post } # This would implicitly serialize using a corresponding serializer?
)
end
end
At the moment, manual steps are required to make CSRF protection work with Rails and Inertia.
To make CSRF protection work out of the box I'm proposing to add the following to the inertia-rails adapter:
XSRF-TOKEN
cookie, that will automatically be picked up by Axios.request_authenticity_tokens
method to also check the X-XSRF-TOKEN
header value (in addition to the X-CSRF-TOKEN
header), since that is what Axios sends by default.Inertia doesn't work in Rails Engine. It selects Main App's Application layout. Added initializer to engine but it is not getting picked up, and Inertia selects App's layout.
Could you please confirm whether this works in a Rails engine?
Thanks
I am trying to make an SSR version, using the inertia-rails
library.
I have added initializers
to configure ssr_enabled
option as documented here.
I do not have any clue what to do next! Could you help me in identifying the next steps, like
@inertia/server
library.Thanks in advance
How do you access variables from server?
Inertia docs showes it by erb (<%= var %>)
But, i cannot name my file to something like index.svelte.erb
.
Recently, the gem rack
was released as v2.1.0 and v2.1.1 with lots of changes.
These updates are not compatible with inertial-rails - the test suite fails:
Failures:
1) InertiaRails::Middleware the version is stale tells the client to refresh
Failure/Error: get empty_test_path, headers: {'X-Inertia' => true, 'X-Inertia-Version' => 'blkajdf'}
NoMethodError:
undefined method `[]' for nil:NilClass
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/rack-2.1.1/lib/rack/etag.rb:38:in `call'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/rack-2.1.1/lib/rack/conditional_get.rb:27:in `call'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/rack-2.1.1/lib/rack/head.rb:14:in `call'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/actionpack-6.0.2.1/lib/action_dispatch/http/content_security_policy.rb:18:in `call'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/rack-2.1.1/lib/rack/session/abstract/id.rb:277:in `context'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/rack-2.1.1/lib/rack/session/abstract/id.rb:271:in `call'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/actionpack-6.0.2.1/lib/action_dispatch/middleware/cookies.rb:648:in `call'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/actionpack-6.0.2.1/lib/action_dispatch/middleware/callbacks.rb:27:in `block in call'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/callbacks.rb:101:in `run_callbacks'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/actionpack-6.0.2.1/lib/action_dispatch/middleware/callbacks.rb:26:in `call'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/actionpack-6.0.2.1/lib/action_dispatch/middleware/executor.rb:14:in `call'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/actionpack-6.0.2.1/lib/action_dispatch/middleware/actionable_exceptions.rb:17:in `call'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/actionpack-6.0.2.1/lib/action_dispatch/middleware/debug_exceptions.rb:32:in `call'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/actionpack-6.0.2.1/lib/action_dispatch/middleware/show_exceptions.rb:33:in `call'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/railties-6.0.2.1/lib/rails/rack/logger.rb:38:in `call_app'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/railties-6.0.2.1/lib/rails/rack/logger.rb:26:in `block in call'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/tagged_logging.rb:80:in `block in tagged'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/tagged_logging.rb:28:in `tagged'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/tagged_logging.rb:80:in `tagged'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/railties-6.0.2.1/lib/rails/rack/logger.rb:26:in `call'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/actionpack-6.0.2.1/lib/action_dispatch/middleware/remote_ip.rb:81:in `call'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/actionpack-6.0.2.1/lib/action_dispatch/middleware/request_id.rb:27:in `call'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/rack-2.1.1/lib/rack/method_override.rb:24:in `call'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/rack-2.1.1/lib/rack/runtime.rb:24:in `call'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activesupport-6.0.2.1/lib/active_support/cache/strategy/local_cache_middleware.rb:29:in `call'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/actionpack-6.0.2.1/lib/action_dispatch/middleware/executor.rb:14:in `call'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/actionpack-6.0.2.1/lib/action_dispatch/middleware/static.rb:126:in `call'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/rack-2.1.1/lib/rack/sendfile.rb:113:in `call'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/actionpack-6.0.2.1/lib/action_dispatch/middleware/host_authorization.rb:77:in `call'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/railties-6.0.2.1/lib/rails/engine.rb:526:in `call'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/rack-test-1.1.0/lib/rack/mock_session.rb:29:in `request'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/rack-test-1.1.0/lib/rack/test.rb:266:in `process_request'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/rack-test-1.1.0/lib/rack/test.rb:119:in `request'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/actionpack-6.0.2.1/lib/action_dispatch/testing/integration.rb:270:in `process'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/actionpack-6.0.2.1/lib/action_dispatch/testing/integration.rb:18:in `get'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/actionpack-6.0.2.1/lib/action_dispatch/testing/integration.rb:357:in `block (2 levels) in <module:Runner>'
# /Users/ledermann/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/rails-controller-testing-1.0.4/lib/rails/controller/testing/integration.rb:13:in `block (2 levels) in <module:Integration>'
# ./spec/inertia/middleware_spec.rb:4:in `block (3 levels) in <top (required)>'
Some further investigations required. Maybe it's a bug in Rack.
With v2.0.8 it works fine.
Rails 5.2 added support for default values in module accessors, i.e.
mattr_accessor, default: 'some value'
That means the Inertia config doesn't work on < Rails 5.2.
There's something strange happening with the inertia_rails gem: Whenever it is included in the Gemfile, Rails stops showing full errors messages in development mode and only servers the 500.html file whenever there is an error. It doesn't matter if the error is Inertia-related or not...
I noticed inside of the inertia gem that it is just rails marked as the dependency. Would it be possible to reduce it to just railties or the action/active deps that required by inertia_rails?
It would be ideal to tell inertia rails that when a partial load is done (e.g only: ["some_prop"]
) only that prop is computed. In order to do this, we need an auxiliary method that allows us to skip props on partial loads.
For example, if we have:
inertia_share do
{
heavy_prop: SomethingHeavyToCompute.get,
notifications: NotificationsSerializer.one(current_user)
}
end
And then in the frontend we do:
router.reload({ only: ["notifications"] })
heavy_prop
is not rendered, but it is computed. This is not ideal when we want to work with partial loads.
The only way I can think this can be achieved is by making heavy props excluded on partial loads:
inertia_share do
{
heavy_prop: InertiaRails.on_full_load(-> { SomethingHeavyToCompute.get }),
notifications: NotificationsSerializer.one(current_user)
}
end
Is this something appealing for anyone else? If so, I can work on it and send a PR.
inertia_rails
version: 3.0The javascript event listeners are not attached to the HTML even after hydrating
.
Example: let's assume there is an event handler registered for an input field named name
. Whenever the user changes the value in the text field, the event listeners should fire.
Reproduction repository: https://github.com/awkward-minion/inertiajs-react-form-handlers.git
The browser renders this problem without any issues.
But the event handlers like handleSubmit
and handleChange
are not registered after the hydration.
hydrateRoot
was not displaying any warnings, considering it as good. The javascript bundle
is being loaded in the browser. (the event handlers)Raised issue in inertia.js
rails repository
Hi - first off, thanks for Inertia. I'm having a great time with it so far!
I'm using Rails 6 + Svelte.js currently, and I'm wondering if anyone has any experience with using HAML to template their svelte components? I'd love to be able to write HAML for these instead of raw HTML.
I can't find the rdoc for this Gem. Is it available somewhere?
Looking at the generators I was checking that the vue installer only works for webpacker apps, which in Rails 7 is not gonna be the main way to go. Will this be updated anytime soon?
I'm playing around with inertia_rails
within a Rails 6 application like this:
class ApplicationController < ActionController::Base
inertia_share do
{
foo: 42
}
end
end
This works fine on the first request (props include foo:42
), but all subsequent requests fail (props not include foo:42
). When I modify my source file (application_controller.rb
) and change foo
to 43, it works on the following one request, but the next requests will fail again.
This can be reproduced with the test suite when you swap the order of the two context blocks in this file:
inertia-rails/spec/inertia/sharing_spec.rb
Lines 4 to 18 in a27564b
Seems to be caused by #13.
Hi guys
I'm probably doing something wrong but whenever I have a form on a page like /posts/new
and I press Save
and my create
action in my controller uses redirect_back
nothing happens. It creates the item but it doesn't redirect back.
It seems there aren't any examples of this in the documentation since it's always redirect_to posts_path
or something similar, but I need more flexibility than that.
Can anybody point me in the right direction?
Cheers!
Using inertia_rails
v1.4.0 can abort application start with this error message (caused by #38):
NoMethodError: undefined method `thread_mattr_accessor' for InertiaRails:Module
Example here:
https://github.com/ledermann/pingcrm/pull/235/checks?check_run_id=856003834
Not every Rails application is affected. If an application uses require "rails/all"
(see The Rails Initialization Process), all works fine, because ActionText
requires this module explicitly. But if the frameworks are picked selectively (leaving out ActionText
), the module may be missing and the startup may fail.
There is a workaround by adding this line to application.rb
of the application:
require "active_support/core_ext/module/attribute_accessors_per_thread"
As a fix, this require
statement should be added to the gem.
We would like to be able to switch layout erb files, imagine a share page with meta tags etc. It would be great if you could pass the desired layout to render inertia
or use the default when necessary
Hi, thanks for inertia. I'm not getting how you can build a web app with Inertia, Rails, and React with no API.
I understand how you can avoid having endpoints for listing resources - in your controllers, use ActiveRecord to list the resources, and then pass the list of resources as props to inertia.
But how do you avoid having endpoints for creating/updating/deleting resources? The PingCRM examples I've seen have API endpoints for create, update, etc. which are called by the UI.
In the after_action I get an error, where the cookie is null:
require_relative "inertia_rails"
require_relative "helper"
module InertiaRails
module Controller
extend ActiveSupport::Concern
included do
before_action do
# :inertia_errors are deleted from the session by the middleware
InertiaRails.share(errors: session[:inertia_errors]) if session[:inertia_errors].present?
end
helper ::InertiaRails::Helper
after_action do
cookies['XSRF-TOKEN'] = form_authenticity_token unless request.inertia? || !protect_against_forgery?
end
end
cookies['XSRF-TOKEN'] = form_authenticity_token unless request.inertia? || !protect_against_forgery?
Resulting in this error
undefined method `[]=' for nil:NilClass
We're using Inertia for a new web app and loving things so far. We do currently have an issue where the inertia_share doesn't seem to run consistently on initial page load?
The rendered props are there and correct in the data-page
attribute but the shared props are nowhere to be seen. A reload typically fixes this but it's pretty bad in our instance since we share a layout
prop which renders an application shell
hello,
I want to test inertia but i can't install the inertia-rails gem as specified in doc.
i tested 3 ways:
And not found on rubygems.org when i search for inertia-rails
screen capture:
https://pbs.twimg.com/media/EF4-xSLXkAERhJu?format=png&name=900x900
https://pbs.twimg.com/media/EF4-xSLXYAECUrg?format=png&name=900x900
Can you help me?
I have recently switched from WebpackerSvelte to Inertia.js for using Svelte components with a Rails backend, but one feature I don't seem to be able to replicate is the ability to render a Svelte component into the middle of an ERB template. With WebpackerSvelte, I was able to do something like
<%= svelte_component('Name', something: 'value') %>
and it would just work, but inertia-rails doesn't seem to work for that. Am I missing something, or is there no way to do this?
I haven't found anything about setting up hot module reload in this context. In an SPA setup Webpack would handle it all through the dev server, I'm wondering if such a setup is possible here. Would appreciate any pointers!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.