PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label ruby-on-rails-3. Show all posts
Showing posts with label ruby-on-rails-3. Show all posts

Friday, October 21, 2022

[FIXED] How to pass an :id to a link_to through a has_many :through relationship to delete a join table column. (Rails)

 October 21, 2022     has-many, relationships, ruby-on-rails, ruby-on-rails-3     No comments   

Issue

This is my first post on StackOverflow, and I'm relatively new to coding in general, so I apologize in advance if I accidentally make some breach of etiquette.

I'm trying to delete a collaborator to a wiki that has been added by the owner, but now he wants to remove their permissions.

This is done from within my wiki#edit view:

<div class="row">
<%= render partial: 'wikis/form' %>
<br>
<%= render partial: 'collaborators/collaborator'%>

<h3> Collaborators: </h3>
<% @wiki.users.each do |c| %>
  <li><%= c.username %></li>
  <% if @wiki.user == current_user && current_user.premium? %>
    <%= link_to "", wiki_collaborator_path(@wiki, @collaborators), method: :delete, remote: true, class: "glyphicon glyphicon-remove"  %>
  <% end %>
<% end %>

The wikis/_form partial is pretty standard:

<div class="col-md-8">
<div class="form-group">
  <%= f.label :title %>
  <%= f.text_field :title, class: 'form-control', placeholder: "Enter wiki title" %>
</div>
<div class="form-group">
  <%= f.label :body %>
  <%= f.text_area :body, rows: 8, class: 'form-control', placeholder: "Enter wiki body" %>
</div>

<% if current_user.admin? || current_user.premium? %>
<div class="form-group">
  <%= f.label :private, class: 'checkbox' do %>
    <%= f.check_box :private %> Private wiki
    <% end %>
</div>
<% end %>

<div class="form-group">
  <%= f.submit "Save", class: 'btn btn-primary' %>
</div>
  <% end %>
</div>

and the collaborators/_collaborator partial creates the initial collaborator:

 <% if @wiki.user == current_user && current_user.premium? %>
  <%= form_for [@wiki, Collaborator.new] do |f| %>
  <%= email_field_tag :collaborator %>
  <%= f.submit "Add collaborator", class: 'btn btn-primary' %>
  <% end %>
<% end %>

This is the Collaborator controller:

  before_action :set_wiki
  def create
    @collaborator = User.find_by_email(params[:collaborator]) #pulled from email tag in collaborator form_for partial
    Collaborator.create(user_id: @collaborator.id, wiki_id: @wiki.id)

    if @collaborator.save
       flash[:notice] = "#{@collaborator.username} at #{@collaborator.email} has been added as a collaborator to #{@wiki.title}"
    else
       flash[:error] = "Adding of collaborator failed"
    end
    redirect_to @wiki
  end

  def delete
    @collaborator = @wiki.users.find(params[:id])

    if @collaborator.destroy
       flash[:notice] = "#{@collaborator.username} at #{@collaborator.email} has been removed from wiki: #{@wiki.title}"
    else
       flash[:error] = "Removal of collaborator failed"
    end
    redirect_to @wiki
  end
private
  def set_wiki
    @wiki = Wiki.find(params[:wiki_id])
  end
end

The Collaborator Model just belongs_to both User and Wiki, and The Wiki model looks like this:

class Wiki < ActiveRecord::Base
  belongs_to :user
  validates :user, presence: true
 #Final refactoring eliminates need for delegate method
 has_many :collaborators, dependent: :destroy
 has_many :users, through: :collaborators
 scope :visible_to, -> (user) { user ? all : where(private: false) }
  validates :title, length: { minimum: 5 }, presence: true
  validates :body, length: { minimum: 20 }, presence: true
end

The error I'm getting back from my local server is

No route matches {:action=>"destroy", :controller=>"collaborators", :id=>nil, :wiki_id=>"104"} missing required keys: [:id]

I've looked everywhere to solve this problem, but I inherently have some trouble understanding the nested routing for has_many :through associations and when I look for answers it seems like everyone has written their method calls differently than mine. Everything in my app functions except this link_to method, so I'd rather not rewrite it just to match someone else's code unless I really messed up somewhere.

I've tried putting @collaborator.id as well as a few other things just to try to brute force a solution, but nothing is working and I have no idea what I'm looking for here.

Any help at all would be greatly appreciated. Thank you ^^


Solution

No route matches {:action=>"destroy", :controller=>"collaborators", :id=>nil, :wiki_id=>"104"} missing required keys: [:id]

The base problem is here:

<%= link_to "", wiki_collaborator_path(@wiki, @collaborators), method: :delete, remote: true, class: "glyphicon glyphicon-remove"  %>

The error states that your @collaborators var does not pass the singular id to the link_to method. This is because I presume @collaborators to be a collection.

--

You need to pass a single collaborator object:

<%= link_to "", wiki_collaborator_path(@wiki, c) ...

Since you're using a .each loop with @wiki.users, each user (which I presume to be a collaborator) has the local variable of c assigned:

<% @wiki.users.each do |c| %>

Since you're new, I'd strongly recommend using font-awesome-rails over glyphicon. The main benefit is the fa_icon helper, which would allow you to use:

<%= link_to fa_icon("close"), wiki_collaborator_path(@wiki, c), method: :delete, remote: true %>


Answered By - Richard Peck
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, July 26, 2022

[FIXED] What are the default values for Rails 3 for :dependent on has_many and belongs_to

 July 26, 2022     belongs-to, default-value, has-many, ruby-on-rails, ruby-on-rails-3     No comments   

Issue

In rails 3, i know that i can force deletion of dependent objects on belongs_to and has_many relations using the :dependent => :delete option. However i was wondering,

what is the default behavior if i do not specify :dependent => ...

Cheers, Hajo


Solution

The documentation says, "When no option is given, the behavior is to do nothing with the associated records when destroying a record." That is, deleting or destroying an object will not delete or destroy the objects that it belongs to or has many of.



Answered By - Rob Davis
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, May 18, 2022

[FIXED] How do I get this variable to be defined?

 May 18, 2022     partial, ruby, ruby-on-rails, ruby-on-rails-3, variables     No comments   

Issue

I have this code:

  <% @registered_friends.each do |friend| %>    
      <li><%= render 'profiles/fb_follow_form' %></li>
  <% end %>

It renders a partial in a different directory with this line:

<% if current_user != nil && current_user.following?(friend) %>

However my app is telling me that friend is undefined? How do I give myself access to the variable?


Solution

Changing <li><%= render 'profiles/fb_follow_form' %></li>

to <li><%= render 'profiles/fb_follow_form', :friend => friend %></li>

should do it



Answered By - AaronThomson
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to render a partial from another namespace in Rails 3?

 May 18, 2022     partial, ruby-on-rails-3     No comments   

Issue

In my Rails 3 project I have:

namespace :admin do
  resources :users
end

scope :frontend do
  resources :users
end

There is a partial with filename "/views/admin/users/_form_fields.html.haml".

And I want to render it from "/views/frontend/users/_form.html.haml".

This code doesn't work:

render 'admin/users/form_fields', :f => f

Solution

To pass local variables you need this sintax:

render :partial => "/admin/users/form_fields", :locals => { :f => f }

Hope this helps. you can take a look to Rails Guide: Using Partials



Answered By - JCorcuera
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to access attributes in a partial of a nested rails form?

 May 18, 2022     forms, nested-forms, partial, ruby-on-rails-3     No comments   

Issue

I want to use the boolean attribute is_white from my inner_object to switch between html code in the the partial _inner_object_form_fields. This is my attempt.

<%= form_for @outer_object do |f| %>
  <%= f.fields_for :inner_object do |builder| %>
    <%= render :partial => "inner_object_form_fields", :locals =>  { :f => builder } %>
  <% end %>
<% end %>

This is my attempt of the partial _inner_object_form_fields.

<% if f.is_white == true %>
  <%= f.label(:name, "White") %>
<% else %>
  <%= f.label(:name, "Black") %>
<% end %>

This is the migration file of InnerObjects.

class InnerObjects < ActiveRecord::Migration
  def self.up
    create_table :inner_objects do |t|
      t.string "name"
      t.boolean "is_white", :default => true
      t.timestamps
    end
  end
  def self.down
    drop_table :inner_objects
  end
end

I found a similar question but could not retrieve an answer for me. The question is: How can access the attribut is_white? My example does NOT work.


Solution

Try

<% if f.object.is_white == true %>

Seem to remember you could access the object this way (not 100% sure though ;)



Answered By - oliverbarnes
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why do I have this "undefined method form" with my RoR app?

 May 18, 2022     forms, partial, ruby-on-rails, ruby-on-rails-3     No comments   

Issue

I have a partial

= form.fields_for :cycles do |c|
  %tr{:style=>"border-right:none;"}
%td{:width=>"16%"}
  = c.text_field :day, :size=>6
  = c.hidden_field :id
%td{:width=>"35%"}= c.text_field :hour, :size=>15
%td{:width=>"35%"}= c.text_field :hour_night, :size=>15
%td{:style => "width:7%;padding:0;border-right:none",:align=>"center"}
  = c.hidden_field :_destroy
  = link_to image_tag("panel_tools/delete.png",:size=>"15x15"), nil, :href =>"", :onclick => "check_nested_attr_destroy(this);return false;" 

I call this from the view like this

= form_for(@schedule_of_working, @new_action ? {:url => schedule_of_workings_path} : {:url => schedule_of_working_path, :method=> :put}) do |f| 
.....
= render(:partial=>'cycles', :collection => @schedule_of_working.cycles, :locals => {:form => f}) if @schedule_of_working.cycles.count > 0

I'm getting an error about undefined method form..

rails -v 3.1.0


Solution

Rails only really works well when you follow its conventions.

You should avoid using: hidden fields, put with a form, passing in the action that way and I'm not sure what you are trying to do with the url in various parts, but anyway avoid these unless you have really good reason why you are not structuring it according to convention. Focus more on your routes and how resources are setup and your models and their relationships and your views should be very minimalist. In them I'm not sure what the hour and hour_night are, or theor length 15. Confusion mix of stuff.

So your form, as is, has a few problems. Rather than specific advice I would just say re-write it. It should be much simpler than this. I would recommend watching some railscasts on forms, e.g.
Forms Part one, two or three



Answered By - Michael Durrant
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I yield a "future" content_for tag in Rails 3?

 May 18, 2022     content-for, partial, ruby-on-rails-3, templates, yield     No comments   

Issue

I have a template with 2 partials. In the first one, I am yieleding content which is only defined in the second partial (with a content_for tag). The problem is that the yield does not recognize that content yet since it was not defined.

If I reverse the order of the partials the yield recognized the content, yet the layout is not as I desire obviously...

Is there a way to do this? Thank you.


Solution

Okay, this was actually an easy fix. I moved the second partial into a content_for block placed above the first partial, and then just yielded it instead of declaring it as a partial.



Answered By - Indigon
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how do i place this ruby code correctly?

 May 18, 2022     erb, partial, ruby, ruby-on-rails, ruby-on-rails-3     No comments   

Issue

I have a piece of code which displays a complicated 'listing' of resources. by complicated i mean that it has name, date, time posted, number of comments, picture, description, and tons more things that you obviously only want to write that block of code one time.

I'm trying to think of how this would go into the rails architecture and I'm at a loss

i need to display the resource listing using a different variable in different controllers. currently its in a partial called _resource_view.html.erb

This is fine for the main listing, but its not usable for the persons profile listing, which takes the same format but shows different resources

_resources_expanded.html.erb

<ul class="res-list">
  <% @resources.each do |resource| %>
    ... list stuff
  <% end %>
</ul>

It uses @resources on index, but on the profile page it uses the same listing code except its @user.resources.each do |resource|

I was thinking maybe something like this but this seems redundant .. and im not even sure if it will work

<ul class="res-list">
  <% @resources.each do |resource| %>
    <%= render 'layouts/resources_expanded' %>
  <% end %>
</ul>

Solution

Don't use instance variables, use local variables in the partial - that lets you pass in a single each time through the @resources.each loop.

<%= render 'layouts/resources_expanded', :resource => resource %>

and then in _resource_view.html.erb change @resource to resource



Answered By - DGM
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to render partial on everything except a certain action

 May 18, 2022     content-for, partial, render, ruby-on-rails-3     No comments   

Issue

I have a _header.html.erb partial which is where I put my navbar

on my launch page I don't want to display the navbar.

this is the body of application.html.erb

<body>
<%= render 'layouts/header' %>
<div id="container">
    <%= yield %>
</div>

</body>

How do I render it on every action except specific actions on specific controllers?


Solution

Replace your render with this:

<%= render 'layouts/header' unless @disable_nav %>

Then you can simply set disable_nav to true in any controller action you like:

def landing_page
  @disable_nav = true
end

As a before_filter, which I'd encourage over the above:

application_controller.rb

def disable_nav
  @disable_nav = true
end

my_controller

before_filter :disable_nav, only: [:landing_page]


Answered By - Damien Roche
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to render partial.js in rails 3

 May 18, 2022     javascript, partial, ruby-on-rails, ruby-on-rails-3     No comments   

Issue

Using rails3 - I have a project with many tasks. I want to use javascript to build the UI for each task. I figured I could display those tasks on the projects show page by rendering a javascript partial for each. I can't get 'tasks/show' to see tasks/show.js.erb Any ideas?

In projects/show.html.erb

<div id="tasks">
<%= render(:partial => "tasks/show", :collection => @project.tasks) %> 
</div>

tasks/show.js.erb

$("tasks").append(new TaskWidget(task.id))

I get the errors

ActionView::MissingTemplate in Projects#show 

Missing partial tasks/show with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>[:html], :locale=>[:en, :en]} in view paths .... around line #13

Thanks


Solution

Shouldn't it be in the file _show.js.erb?

From "Using Partials".



Answered By - wombleton
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, April 14, 2022

[FIXED] How do I change a string column into a bigint?

 April 14, 2022     heroku, migration, postgresql, ruby-on-rails, ruby-on-rails-3     No comments   

Issue

In rails migration. How do I change a string type column to a bigint?

I have:

t.change :ip_number_from, :integer, :limit => 8

I

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, April 13, 2022

[FIXED] What is the best way to resolve Rails orphaned migrations?

 April 13, 2022     git, migration, rails-migrations, ruby-on-rails, ruby-on-rails-3     No comments   

Issue

I have been switching between branches in a project and each of them have different migrations... This is the scenario:

$ rake

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I rename a database column in a Ruby on Rails migration?

 April 13, 2022     alter-table, migration, rename, ruby-on-rails, ruby-on-rails-3     No comments   

Issue

I wrongly named a column hased_password instead of hashed_password.

How do I update the database schema, using migration to rename this column?

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing