0

in my index.html.erb i'd like to save my settings to the database.

My settings are stored here

<%= javascript_tag do %>
window.settings = <%= raw Setting.where("shopify_domain = '#{@currentShop.domain}'").to_json %>
<% end %>

Now i'd like to write back my settings to the database by calling this function

function writeSettings() {

  alert(settings[0].id); //this is working

  <%=  Setting.update(settings[0].id, :appearance => 'box') %> //not working unknown variable settings

}

How can i update my record?

Or, how can i call this function with parameters in my settings.rb file

# PATCH/PUT /settings/1
# PATCH/PUT /settings/1.json
def update
respond_to do |format|
  if @setting.update(setting_params)
    format.html { redirect_to @setting, notice: 'Setting was successfully updated.' }
    format.json { render :show, status: :ok, location: @setting }
  else
    format.html { render :edit }
    format.json { render json: @setting.errors, status: :unprocessable_entity }
  end
end
end
3
  • You need to get your JS to update your html - then pluck the value of the id from the html using div selectors - if you have your setting_id stored in a div 'setting-id' then you need: document.getElementById("school_id_school_id").value Commented Feb 2, 2018 at 14:46
  • can you send me a working example? i don't get it :( So this stackoverflow.com/a/8109345 is what im looking for? Commented Feb 2, 2018 at 15:02
  • Sorry ignore the above will give a separate answer Commented Feb 2, 2018 at 15:14

2 Answers 2

0

https://jing.io/t/pass-javascript-variables-to-rails-controller.html

There's probably better ways to approach it but that link should get your method working

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry but, none of these methods are working with the latest rails version
0

In Rails, you must reload the page in order for the controller methods to be used. So, you can't just call it in the middle of the page, after the page has completely loaded. You need to use the client to send the call to the server. In your function, instead of rails, do an ajax call.

Here's a good starter method:

       $.ajax({
            url: '/settings/' + settings[0].id,
            type: 'POST',
            data: {
                setting: {
                    appearance: 'box,
                }
            },
            success: function(result)   {
                console.log('success!')
            },
            error: function(err)    {
                console.log(err);
            }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.