RoR新手求助:如何结合link_to与JS传递双参数至控制器create方法
Hey there! I remember struggling with exactly this kind of thing when I was new to Rails and DataTables—let's walk through how to get this working properly.
First: Fixing the AJAX ($.get) Approach
Your initial AJAX attempt had two main issues: you were passing current_user.id as a string instead of the actual value, and using GET for a create action (which should use POST per RESTful conventions). Here's how to fix it:
- Update your JS to pass the correct values:
Make sure your JS file is an.erbfile (likeyour_view.js.erb) so you can embed Rails variables directly, or add this script inside your ERB view file:// Bind to your button's click event $('.add-btn').on('click', function() { // Get the selected row's h_id (adjust this to match how you store the ID in your row) const selectedHId = $('.dataTable').DataTable().row('.selected').data().h_id; // Or if you're using data attributes on the row: // const selectedHId = $('.dataTable .selected').data('h-id'); // Send a POST request to your create action $.post('/mycontroller/create', { h: { user_id: <%= current_user.id %>, h_id: selectedHId } }) .done(function() { alert('Successfully added to your list!'); // Optional: Refresh your DataTable or update the UI $('.dataTable').DataTable().ajax.reload(); }) .fail(function() { alert('Oops, something went wrong.'); }); });
Second: Fixing the link_to Approach
The problem with link_to is that it's rendered on the server, so it can't access the dynamically selected row's h_id from the frontend. We can work around this by using JS to inject the h_id when the button is clicked:
Create the link with a base URL:
<%= link_to "Add to h-list", "#", method: :post, class: "btn btn-default add-link", data: { base_url: my_controller_create_path } %>Add JS to handle the click:
$('.add-link').on('click', function(e) { e.preventDefault(); // Stop the default link behavior const selectedHId = $('.dataTable').DataTable().row('.selected').data().h_id; const baseUrl = $(this).data('base_url'); // Send the POST request with both parameters $.post(baseUrl, { h: { user_id: <%= current_user.id %>, h_id: selectedHId } }) .done(function() { // Handle success (e.g., show a notification) }); });
Third: Handling Parameters in the Controller
You need to use strong parameters to safely accept the values and create your model instance. Here's how to update your controller:
def create @h = H.new(h_params) # Make sure your model name is capitalized (H, not h) if @h.save # Redirect or send a success response redirect_to your_target_path, notice: 'Added to your list successfully!' else # Handle errors (e.g., validation failures) redirect_to :back, alert: "Couldn't add: #{@h.errors.full_messages.join(', ')}" end end private # Strong parameters to whitelist allowed inputs def h_params params.require(:h).permit(:user_id, :h_id) end
Key Notes:
- Always use
POSTfor create actions (Rails routes expect this for RESTful resources). - Nesting parameters under
h:matches how Rails expects model attributes, making strong parameters easier to handle. - Double-check that you're correctly fetching
h_idfrom your DataTable row—adjust the JS selector if your row stores the ID differently (e.g., data attributes, hidden columns).
内容的提问来源于stack exchange,提问作者Awesome

