else render 'edit' end end private def load_post @post ||= Post.find(params[:id]) end def build_post @post ||= Post.new @post.attributes = post_params end def post_params params.fetch...

...title, presence: true end app/controllers/posts_controller.rb def edit load_post - build_post end def post_params + params.with_defaults!(post: { tags: [] }) params.fetch(:post, {}).permit( :title, + tags: [], ) end app/views/posts/_form.haml = form_with(model: @post...

...provide an action that takes the name of a category from the user input params and loads all the notes in that category: class NotesController < ApplicationController def category @notes = Note.scoped...

...conditions => { :category => params[:category] }, :order => 'created_at DESC') end end So far, the code is fine. We will now introduce the bug by preloading the Note#author association: class NotesController...

...or simply let go of the validation. Your controller is slicing away the nested parameters. You are not building the right amount of associated records in the required controller actions...

...f.object.send(nested_association).klass.new. You have not added the id attribute into the nested params: params.permit(:attribute_1, ..., nested_attributes: [:id, ...]). This will render additional records from the last cached...

makandra dev

...controller action class SomeController < ActionController::Base def old_location redirect_to(new_location_url(params.permit(:foo))) end end This will: It will redirect with a 302 status code

...raise ActionController::UnfilteredParameters if there is any other query param than foo, e.g. https://www.example.com/old_location?another_param=1. This is because url_for will call to_h on ActionController::Parameters, which will...

...during development and in tests. Consider this approach if you want to strengthen the params handling in your application. Example # config/application.rb config.action_controller.action_on_unpermitted_parameters = :raise def user_params params.require...

...user).permit(:full_name) end Effects This raises an error ActionController::ParameterMissing if there is no required parameter: In production users see a bad request error page. In production the...

millarian.com

...reduces repetitions in the binding list. Example without named bindings User.where( 'name = ? OR email = ?', params[:query], params[:query] ) Example with named bindings User.where( 'name = :query OR email = :query', query: params...

...exception: false) # 3 This is typically useful for casting a user defined parameter to an Integer without causing exception notifications: # can cause exceptions def show # there's no guarantee that...

...params[:page] is something that can be cast to an Integer Record.paginate(page: params[:page]) end # will not raise because of a failed typecast def show Record.paginate(page: Integer(params...

...array of records or scope of records: class UsersController < ApplicationController def show @user = User.find(params[:id]) fresh_when @user end def index @users = User.all.to_a fresh_when @users end

...array of ETaggable objects to fresh_when. class UsersController < ApplicationController def show @user = User.find(params[:id]) # The show template also renders the user's posts. fresh_when [@user, *@user.posts]

# This is NOT!! safe, even though we used `safe_constantize` user_input = params[:class_name] user_input.safe_constantize.new An attacker could craft a request with a malicious class_name such...

...allowlist, the application ensures that only valid and expected constants are resolved: class_name = params[:type].presence_in(%w[User Post Test]) if class_name class_name.safe_constantize.new # either User, Post or...

masilotti.com

...new user fixture is created test "user can be created" do post users_path, params: { first_name: "Foo", last_name: "Bar" } assert User.count == 3 end Good example: test "user can...

assert_difference "User.count", 1 do post users_path, params: { first_name: "Foo", last_name: "Bar" } end end Conclusion Benefits You tests will become more explicit by default...

When an AJAX request raises an exception on the server, Rails will show a minimal error page with only basic...

end When whitelisting the avatar field in the controller, you might do this: params[:user].permit(:avatar) But you probably want this: params[:user].permit(:avatar, :avatar_cache, :remove...

...default plugin and passing overrides. Example: const { data } = svgo.optimize(svg, { plugins: [ { name: 'preset-default', params: { overrides: { convertTransform: false } } }, ], }) While not recommended, you may also not use preset-default to keep...

...API to make your live easier if you want to get or manipulate query parameters (URL parameters). URLSearchParams API The URLSearchParams API is supported in all major browsers except IE...

...It offers you a bunch of useful methods: URLSearchParams.append() - appends a query parameter URLSearchParams.delete() - deletes the specified query parameter URLSearchParams.get() - returns the value of the specified query parameter URLSearchParams.has() - checks...

...both scopes with scope_a.where(id: scope_b): class DealDocumentsController < ApplicationController def index @deal = current_power.deals.find(params[:deal_id]) @documents = current_power.documents.where(id: @deal.documents) # <-- Here end end You can also merge scopes for...

...power :notes, map: { ..., [:attachment] => :downloadable_attachment_notes }, as: :note_scope def attachment note = note_scope.find(params[:id]) send_file note.attachment.path end end downloadable_attachment_notes is your power that regulates which...

...internal method with a controller action. Examples for internal methods: #process #process_action #cookies #params #request #response Debugging If you accidentally did overwrite some internal method, you may come across...

...messages will be hard to read. Instead, consider doing this: SomeApi.should_receive(:find) do |params| params[:query].should == '*foo*' params[:sort].should == 'timestamp ASC' params[:limit].should == 100 ['some result...

...preload associations for loaded objects like this: class UsersController < ApplicationController def show @user = User.find(params[:id]) @user.preload_associations(threads: { posts: :author }, messages: :sender) end end The attached initializers remain for...

If in your application your users pass along params that result in filenames, like invoices/generated?number=123. This could be your (very careless) controller method: def generated send_file File.join...

...Rails.root, 'shared', 'invoices', params[:number]) end This allows your users not only to access those files but also any files your application can read, like this: invoices/generated?number=../../../../../etc/passwd

...fields. You need to write the 7 inputs by hands and permit the 7 params one by one. No extra convenience here. You can at least extract this to a...

...a before_action. class NotesController power :notes # Authorization through Consul def attachment note = Note.find(params[:id]) send_file note.attachment.path end end Connect the action in your config/routes.rb: map.resources :notes, :member...

...so its inputs will not live inside your form. This will result in losing params because they will not be submitted along. To fix this, we need to create a...

...method (default enabled), :uri (default enabled), :body, :headers, :host, :path, :query). If e.g. your params have a different order, this might fail in the comparison of equality:

...compatible request matcher Body with ignored order URI ignoring query parameter ordering 1 URI ignoring query parameter ordering 2 Tests with AJAX Using javascript in integration tests might cause issues...