I am using Rails 6 API and React. I'm trying to build a Rich Text Editor with ActionText. When I send the RTE content from the Trix editor on the front end, it just doesn't set the ActionText body to the body I sent through with Axios.
I am sure that the body has come correctly to the controller because I used byebug and printed out the param value.
For example, it looked like this: <div><!--block-->test</div>
But whenever I try to view what it actually is by running announcement.details.to_s it returns " " for some reason.
I set the details field like this: has_rich_text :details in the Announcement model.
My controller which handles this looks like this:
module V1
class AnnouncementsController < ApplicationController
def create
announcement = Announcement.new(announcement_params)
announcement.author = #current_user
authorize announcement
if announcement.valid? && announcement.save
render json: { message: "Announcement successfully created! You can view it here." }, status: 201
else
render json: { messages: announcement.errors.full_messages }, status: 400
end
end
private
def announcement_params
params.require(:announcement).permit(:title, :details)
end
end
end
If it helps in any way, this is the React code:
const RTE = (props) => {
let trixInput = React.createRef()
useEffect(() => {
trixInput.current.addEventListener("trix-change", event => {
console.log("fired")
props.onChange(event.target.innerHTML)
})
}, [])
return (
<div>
<input
type="hidden"
id="trix"
value={props.value}
/>
<trix-editor
input="trix"
data-direct-upload-url={`${bURL}/rails/active_storage/direct_uploads`}
data-blob-url-template={`${bURL}/rails/active_storage/blobs/:signed_id/*filename`}
ref={trixInput}
className="trix-content"
></trix-editor>
</div>
);
}
And then I just normally pass it with Axios:
axios.post(`${bURL}/v1/announcements/create`, {
"announcement": {
"title": title,
"details": value
}
}, {
headers: {
'Authorization': `token goes here`
}
}).then(res => {
// success
}).catch(err => {
// error
})
If you need any more code snippets or information please comment.
Related
I am currently working on a project using react and ruby on rails. My goal right now is to send a post request using fetch to create and store my user in my backend api on submission of my react form. My problem is, the backend isn't receiving my data correctly, resulting in a 406 error. I feel like i've tried everything, i'm going crazy, help.
REACT CODE:
form-
<form onSubmit={handleSubmit}>
<label>Name:</label>
<input type="text" required value={name} onChange={handleNameChange} name="name" placeholder="name"/>
<label>Password:</label>
<input type="password" required value={password} onChange={handlePasswordChange} name="password" placeholder="password"/>
<input type="submit" value="Create Account"/>
</form>
methods -
const [name, setName] = useState("")
const [password, setPassword] = useState("")
const handleNameChange = (e) => {
setName(e.target.value);
}
const handlePasswordChange = (e) => {
setPassword(e.target.value);
}
const handleSubmit = (e) => {
e.preventDefault();
const data = {name, password}
fetch("http://localhost:3000/users", {
method: 'POST',
body: JSON.stringify(data),
headers: {
Content_Type: "application/json",
}
})
RAILS CODE:
users controller-
def create
user = User.create(user_params)
if user.valid?
payload = {user_id: user.id}
token = encode_token(payload)
render json: { user: user, jwt: token }
else
render json: { error: 'failed to create user' }, status: :not_acceptable
end
end
private
def user_params
params.permit(:name, :password)
end
error -
backend error
It looks like user.valid? returns false, so your else statement kicks in:
render json: { error: 'failed to create user' }, status: :not_acceptable
The status: :not_acceptable generates the 406 error.
You should probably include the reason why user is not valid, and return a bad request response instead:
render json: { error: user.errors.full_messages}, status: :bad_request
I'm trying to store and image to a rails 6 API, but when I try to send the image from the front end it creates a new record but it doesn't attach the image to it, saying my parameter is unpermitted. Here is my code:
BACK-END:
class Avatar < ApplicationRecord
has_one_attached :attachment
end
class AvatarsController < ApplicationController
def create
avatar = Avatar.new(avatar_params)
if avatar.save
render json: avatar, status: :created
else
render json: avatar.errors, status: :unprocessable_entity
end
end
private
def avatar_params
params.require(:avatar).permit(:attachment)
end
end
FRONT-END:
import React from 'react';
import axios from 'axios';
const Avatar = () => {
const handleChange = event => {
const attachment = new FormData();
attachment.append('avatar[attachment]', event.target.files[0]);
axios.post('/api/v1/avatars', { avatar: { attachment } }, { withCredentials: true });
};
return (
<form>
<input type="file" accept="image/*" onChange={handleChange} />
</form>
);
};
export default Avatar;
But when I try to submit it I get this:
Parameters: {"avatar"=>{"attachment"=>{}}}
Unpermitted parameter: :attachment
However the transaction begins and commits successfully, without making the attachment
Here
is a very a very similar question, but that solution didn't work for me either.
I anyone have any idea on how to solve this, I would really appreciate the help.
I am trying to validate User inputs on server side in a Rails Application with React as view. Basically I make axios calls to the Rails API like this:
const Script = props => {
const [script, setScript] = useState({})
const [scene, setScene] = useState({})
const [loaded, setLoaded] = useState(false)
useEffect(() => {
const scriptID = props.match.params.id
const url = `/api/v1/scripts/${scriptID}`
axios.get(url)
.then( resp => {
setScript(resp.data)
setLoaded(true)
})
.catch(resp => console.log(resp))
}, [])
const handleChange = (e) => {
e.preventDefault()
setScene(Object.assign({}, scene, {[e.target.name]: e.target.value}))
}
const handleSubmit = (e) => {
e.preventDefault()
const csrfToken = document.querySelector('[name=csrf-token]').content
axios.defaults.headers.common['X-CSRF-TOKEN'] = csrfToken
const script_id = script.data.id
axios.post('/api/v1/scenes', {scene, script_id})
.then(resp => {
const included = [...script.included, resp.data.data]
setScript({...script, included})
})
.catch(err => {
console.log(err.response.data.error)
})
.finally(() => {
setScene({name: '', description: ''})
})
}
All data gets passed into a react component with a form.
return (
<div className="wrapper">
{
loaded &&
<Fragment>
.
.
.
<SceneForm
handleChange={handleChange}
handleSubmit={handleSubmit}
attributes={script.data.attributes}
scene={scene}
/>
</Fragment>
}
</div>
)
In this form I have a name field and the corresponding name in Rails has a validation uniqueness: true. everything works fine if I enter a valid (unique) name.
I tried to implement a validation but I am not happy with the outcome. (It works in general: my no_errors? method does what is is supposed to do and I get a 403 status) This is the controller part:
def create
scene = script.scenes.new(scene_params)
if no_error?(scene)
if scene.save
render json: SceneSerializer.new(scene).serialized_json
else
render json: { error: scene.errors.messages }, status: 422
# render json: { error: scene.errors.messages[:name] }, status: 423
end
else
render json: { error: "name must be unique" }, status: 403
end
end
.
.
.
private
def no_error?(scene)
Scene.where(name: scene.name, script_id: scene.script_id).empty?
end
If I enter an existing name I get a console.log like this:
screenshot
Here is my concern: I am not happy with my approach of error handling in general. I do not want to get the 403 message logged to the console (I do want to avoid this message in the first place).
My idea is to take the "simple form" approach: Make the border of my field red and post an error message under the field, without any console output...
And on a side note: Is 403 the correct status? I was thinking about 422 but wasn't sure...
Thank you for your ideas in advance!
403 is the wrong status code. What you need is to return a 422 (unprocessable entity). 403 is more about policy and what you are authorized to do.
Then when you deal with http request it's a standard to have a request and status code printed in browser console. Not sur to get your issue here.
If it's about to display the error you could just have a function that colorize (or whatever fireworks you want) your input if the status code response is a 422.
I have the smart buttons "working" in sandbox but I can't think of any way to attach the smart buttons success to the order form which creates the order. With Stripe Elements, it's pretty plug and play because it's on the page and a part of the form itself, but with PayPal with the redirects, I can't seem to think of a way.
Does this require javascript or can I do this without it, aside from what's already there?
Form:
<%= form_for(#order, url: listing_orders_path([#listing, #listing_video]), html: {id: "payment_form-4"} ) do |form| %>
<%= form.label :name, "Your Name", class: "form-label" %>
<%= form.text_field :name, class: "form-control", required: true, placeholder: "John" %>
#stripe code here (not important)
<%= form.submit %>
<div id="paypal-button-container"></div>
<!-- Include the PayPal JavaScript SDK -->
<script src="https://www.paypal.com/sdk/js?client-id=sb¤cy=USD"></script>
<script>
// Render the PayPal button into #paypal-button-container
paypal.Buttons({
// Set up the transaction
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: <%= #listing.listing_video.price %>
}
}]
});
},
// Finalize the transaction
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
// Show a success message to the buyer
alert('Transaction completed by ' + details.payer.name.given_name + '!');
});
}
}).render('#paypal-button-container');
</script>
Create Method in Controller:
require 'paypal-checkout-sdk'
client_id = Rails.application.credentials[Rails.env.to_sym].dig(:paypal, :client_id)
client_secret = Rails.application.credentials[Rails.env.to_sym].dig(:paypal, :client_secret)
# Creating an environment
environment = PayPal::SandboxEnvironment.new(client_id, client_secret)
client = PayPal::PayPalHttpClient.new(environment)
#amount_paypal = (#listing.listing_video.price || #listing.listing_tweet.price)
request = PayPalCheckoutSdk::Orders::OrdersCreateRequest::new
request.request_body(
{
intent: 'AUTHORIZE',
purchase_units: [
{
amount: {
currency_code: 'USD',
value: "#{#amount_paypal}"
}
}
]
}
)
begin
# Call API with your client and get a response for your call
response = client.execute(request)
# If call returns body in response, you can get the deserialized version from the result attribute of the response
order = response.result
puts order
#order.paypal_authorization_token = response.id
rescue BraintreeHttp::HttpError => ioe
# Something went wrong server-side
puts ioe.status_code
puts ioe.headers['debug_id']
end
How can I tie in the PayPal smart buttons with the form so once the payment is completed, it creates an order if successful?
UPDATE:::::::
Created a PaypalPayments controller and model:
controller:
def create
#paypal_payment = PaypalPayment.new
#listing = Listing.find_by(params[:listing_id])
require 'paypal-checkout-sdk'
client_id = "#{Rails.application.credentials[Rails.env.to_sym].dig(:paypal, :client_id)}"
client_secret = "#{Rails.application.credentials[Rails.env.to_sym].dig(:paypal, :client_secret)}"
# Creating an environment
environment = PayPal::SandboxEnvironment.new(client_id, client_secret)
client = PayPal::PayPalHttpClient.new(environment)
#amount_paypal = #listing.listing_video.price
request = PayPalCheckoutSdk::Orders::OrdersCreateRequest::new
#paypal_payment = request.request_body({
intent: "AUTHORIZE",
purchase_units: [
{
amount: {
currency_code: "USD",
value: "#{#amount_paypal}"
}
}
]
})
begin
# Call API with your client and get a response for your call
response = client.execute(request)
# If call returns body in response, you can get the deserialized version from the result attribute of the response
order = response.result
puts order
# #order.paypal_authorization_token = response.id
rescue BraintreeHttp::HttpError => ioe
# Something went wrong server-side
puts ioe.status_code
puts ioe.headers["debug_id"]
end
# if #paypal_payment.create
# render json: {success: true}
# else
# render json: {success: false}
# end
end
Javascript in view:
paypal.Buttons({
createOrder: function() {
return fetch('/paypal_payments', {
method: 'post',
headers: {
'content-type': 'application/json'
}
}).then(function(res) {
return res.json();
}).then(function(data) {
return data.orderID;
});
},
onApprove: function(data) {
return fetch('/orders', {
method: 'post',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
orderID: data.orderID
})
}).then(function(res) {
return res.json();
}).then(function(details) {
alert('Authorization created for ' + details.payer_given_name);
});
},
}).render('#paypal-button-container');
With this, the paypal box appears but then goes away right after it loads with this in the CMD:
#<OpenStruct id="1Pxxxxxxx394U", links=[#<OpenStruct href="https://api.sandbox.paypal.com/v2/checkout/orders/1P0xxxxxxx394U", rel="self", method="GET">, #<OpenStruct href="https://www.sandbox.paypal.com/checkoutnow?token=1P07xxxxxxx94U", rel="approve", method="GET">, #<OpenStruct href="https://api.sandbox.paypal.com/v2/checkout/orders/1Pxxxxxxx4U", rel="update", method="PATCH">, #<OpenStruct href="https://api.sandbox.paypal.com/v2/checkout/orders/1P07xxxxxxx394U/authorize", rel="authorize", method="POST">], status="CREATED">
No template found for PaypalPaymentsController#create, rendering head :no_content
Completed 204 No Content in 2335ms (ActiveRecord: 15.8ms)
I have not used smart buttons. However, you should not have "a ton more code" in a create action. If you are following MVC and rails conventions. It would seem that you need a seperate controller action to handle the payment authorization separately from the create action. But if you can get to this point in your javascript, here is example of how you would send the data from paypal javascript back to your controller, this will need some work but hopefully it points you in the right direction:
// Finalize the transaction
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
// Show a success message to the buyer
alert('Transaction completed by ' + details.payer.name.given_name + '!');
// here is where you should send info to your controller action via ajax.
$.ajax({
type: "POST",
url: "/orders",
data: data,
success: function(data) {
alert(data); // or whatever you wanna do here
return false;
},
error: function(data) {
alert(data); // or something else
return false;
}
});
});
}
This is most likely far too late, but ill add what worked for me.
You need to return the response ID to the PayPal script as a json object. All you need to do is update your create function like so :
...
begin
# Call API with your client and get a response for your call
response = client.execute(request)
# If call returns body in response, you can get the deserialized version from the result attribute of the response
order = response.result
render json: { orderID: order.id }
# #order.paypal_authorization_token = response.id
rescue BraintreeHttp::HttpError => ioe
# Something went wrong server-side
puts ioe.status_code
puts ioe.headers["debug_id"]
end
...
I need to upload an image of my user from my react app to Rails api only server.
My HTML input file
<input ref={(input) => this.profileImage_input = input}
type="file"
name="user-profile-image"
className="small-font-size"
onChange={(e) => this.handleChange(e)}/>
So this is my component upload function.
let profileUploadImage = this.profileImage_input.files;
let user_info = {};
user_info = {
username: this.username_input.value,
profile_image: profileUploadImage
};
this.props.update_user_with_image_server(user_info,this.props.user.user.id)
My actionCreator
export function update_user_with_image_server(user_info,user_id){
let formData = new FormData();
for(let key in user_info) {
if(user_info.hasOwnProperty(key)) {
formData.append(key, user_info[key]);
}
}
return function (dispatch) {
fetch(deafaultUrl + '/v1/users_profile/' + user_id,
{
headers: {
'Content-Type': 'multipart/form-data'
},
method: "PATCH",
body: formData
})
.then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
})
.then(function(json){
});
}
}
My rails user controller
def update_with_image
user = current_user
if user.update_attributes(user_update_params)
# Handle a successful update.
render json: user, status: 200
else
render json: { errors: user.errors }, status: 422
end
end
private
def user_update_params
params.permit(:username,:profile_image)
end
So the problem is it seems like user_update_params didn't workout rails cannot read the data and update in correctly so how could i fix this?
Thanks!